PHP foreach change original array values

Jeppe picture Jeppe · Feb 22, 2013 · Viewed 190.6k times · Source

I am very new in multi dimensional arrays, and this is bugging me big time.

My array is as following:

$fields = array(
    "names" => array(
         "type"         => "text",
         "class"        => "name",
         "name"         => "name",
         "text_before"  => "name",
         "value"        => "",
         "required"     => true,
    )
)

Then i got a function checking if these inputs are filled in, if they are required.

function checkForm($fields){
    foreach($fields as $field){
        if($field['required'] && strlen($_POST[$field['name']]) <= 0){
            $fields[$field]['value'] = "Some error";
        }
    }
    return $fields;
}

Now my problem is this line

$fields[$field]['value'] = "Some error";

I want to change the content of the original array, since i am returning this, but how do I get the name of the current array (names in this example) in my foreach loop?

Answer

Vlad Preda picture Vlad Preda · Feb 22, 2013

In PHP, passing by reference (&) is ... controversial. I recommend not using it unless you know why you need it and test the results.

I would recommend doing the following:

foreach ($fields as $key => $field) {
    if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
        $fields[$key]['value'] = "Some error";
    }
}

So basically use $field when you need the values, and $fields[$key] when you need to change the data.