<?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)
& 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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With