Jump to content

Dont understand this


Go to solution Solved by Jacques1,

Recommended Posts

So I am looking at the code for https://github.com/vlucas/valitron/blob/master/src/Valitron/Validator.php a validation library, and currently trying to interpret the code. Most of it I understand but a part in the constructor is confusing me. It is as follows:

public function __construct($data, $fields = array(), $lang = null, $langDir = null)
    {
        // Allows filtering of used input fields against optional second array of field names allowed
        // This is useful for limiting raw $_POST or $_GET data to only known fields
        $this->_fields = !empty($fields) ? array_intersect_key($data, array_flip($fields)) : $data; 

The part that is confusing me is the $this->_fields line, what exactly is the point of this and could you provide an example for when this when be needed? The part that really gets me is when it gets to array_intersect_key and array_flip, again what is the point of these?

 

Link to comment
https://forums.phpfreaks.com/topic/300818-dont-understand-this/
Share on other sites

The point is to turn the array values of $fields into keys so that they can be passed to array_intersect_key():

<?php

$fields = ['username', 'pass', 'email'];
var_dump($fields);

$flipped_fields = array_flip($fields);
var_dump($flipped_fields);

Using $fields directly wouldn't work, because it has numerical keys which aren't very useful here.

Edited by Jacques1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.