Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: issue with Using Reference Arrays

Tags:

php

<?php 
$fruits = array(' appLE', 'pear3', 'banana--');
$vegetables = array('pea', 'broccoli   ');
$processArr = array(&$fruits, &$vegetables);
foreach($processArr as &$array)
    foreach($array as &$item)
    {
        $item = preg_replace('/[^a-z]/i', '', $item);
        $item = ucwords(strtolower($item));
    }
echo '<pre>';
print_r($fruits);
print_r($vegetables);

Result:

Array
(
    [0] => Apple
    [1] => Pear
    [2] => Banana
)
Array
(
    [0] => Pea
    [1] => Broccoli
)

Question:

I know this one $processArr = array(&$fruits, &$vegetables);, means pass reference of $fruits, $vegetables, if $processArr changed, it will also change $fruits, $vegetables, but I do not understand why also use & in foreach, anyone can explain to me? thanks.

foreach($processArr as &$array)
        foreach($array as &$item)
like image 573
user2294256 Avatar asked Aug 14 '26 14:08

user2294256


1 Answers

& in foreach allows modifying element in an array using reference. If you do not use reference, to modify value, you have to use array keys.

foreach ( $data as &$element ) {
  $element = $element + 'foo';
}

equals

foreach ( $data as $key => $element ) {
  $data[$key] = $element + 'foo';
}
like image 59
hsz Avatar answered Aug 16 '26 17:08

hsz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!