php: issue with Using Reference Arrays -
<?php $fruits = array(' apple', 'pear3', 'banana--'); $vegetables = array('pea', 'broccoli '); $processarr = array(&$fruits, &$vegetables); foreach($processarr &$array) foreach($array &$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 1 $processarr = array(&$fruits, &$vegetables);, means pass reference of $fruits, $vegetables, if $processarr changed, change $fruits, $vegetables, not understand why use & in foreach, can explain me? thanks.
foreach($processarr &$array) foreach($array &$item)
& in foreach allows modifying element in array using reference. if not use reference, modify value, have use array keys.
foreach ( $data &$element ) { $element = $element + 'foo'; } equals
foreach ( $data $key => $element ) { $data[$key] = $element + 'foo'; }
Comments
Post a Comment