3
<?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)
1
  • Good question and well asked Commented Aug 16, 2013 at 9:25

1 Answer 1

3

& 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';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.