Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach change original array values [duplicate]

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?

like image 813
Jeppe Avatar asked Feb 22 '13 12:02

Jeppe


People also ask

Does forEach change the original array?

forEach() does not mutate the array on which it is called.

How to change value in forEach loop in php?

foreach($arr as &$value) { $value = $newVal; } unset($value); & 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.

How do I change the value of a forEach?

To change the value of all elements in an array: Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

What is use of Array_unique in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.


2 Answers

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.

like image 81
Vlad Preda Avatar answered Sep 21 '22 03:09

Vlad Preda


Use &:

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

& 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 any performance improvement. As 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?

like image 30
Dharman Avatar answered Sep 23 '22 03:09

Dharman