[php] PHP foreach change original array values

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?

This question is related to php arrays foreach

The answer is


Try this

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

Use &:

foreach($arr as &$value) {
    $value = $newVal;
}

& passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

PHP documentation for Passing by Reference

Edit 2018

This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach (or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about & operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?


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

This is what I would Suggest pass by reference


Use foreach($fields as &$field){ - so you will work with the original array.

Here is more about passing by reference.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?