arrays - PHP - Need some help on some explanations for this foreach loop -
i have 3 arrays , looking common value each of these arrays.
note: original exercise not use built-in php functions.
i have solution need trying understand specific parts of solution.
can step me through this?
i have questions on following:
1) on first nested foreach foreach ($ar $value), $ar has 3 arrays , taking values of each , putting $value, how work? normal behavior nested foreach arrays?
2) (!isset($values[$value])) { if values array passing in array values variable $value not set equals 0 / why need equal zero?
3) $a = $values[$value]++; why increment here purpose?
4) foreach ($values $value => $count) { can explain last foreach doing? stepping through it?
code
$array1 = [1, 5, 10, 20, 40, 80]; $array2 = [6, 7, 20, 80, 100]; $array3 = [3, 4, 15, 20, 30, 70, 80, 120]; $values = []; foreach ([$array1, $array2, $array3] $ar) { foreach ($ar $value) { if (!isset($values[$value])) { $values[$value] = 0; } $a = $values[$value]++; } } $commonvalues = []; foreach ($values $value => $count) { if ($count > 2) { $commonvalues[] = $value; } } print_r($commonvalues); // common values 20, 80
1) on first nested foreach foreach ($ar $value), $ar has 3 arrays , taking values of each , putting $value, how work? normal behavior nested foreach arrays?
$ar reference current array in array, it's same $array1, $array2, etc1. inner foreach takes array reference , iterates through referenced array, it's reference being current referenced integer value in referenced array.
see foreach documentation in php manual.
2) (!isset($values[$value])) { if values array passing in array values variable $value not set equals 0 / why need equal zero?
isset() checks $values array does have key set, , returns false if not set. ! negation, turns true false , false true. hence, if $value key not set in $values, set value of 0. be...
3) $a = $values[$value]++; why increment here purpose?
... incremented keep track of number of times $value found in [$array1, $array2, $array3] list passed outer foreach.
4) foreach ($values $value => $count) { can explain last foreach doing? stepping through it?
this reading through individual instances of values stored arrays, checking count, , storing value ($value) in $commonvalues array if occurred more twice.
1. technically, $ar copy of related [$array1, ...] array (which in turn copy of actual $array# variable); &$ar mean use reference actual array, not make copy. here demonstration: http://codepad.viper-7.com/hxdsd7 note how $array1 modified other 2 not (since don't have & this: [&$array1, &$array2, &$array3]).
Comments
Post a Comment