i want foreach return arrays returns single array. array_map with same code does.
- what correct way of getting arrays out of
foreach. - why
foreachbehaves differentlyarray_map.
inside file (userdata.php)
reme:reme1991@jourrapide.com george bush:georgebush@gmail.com obama:obama@gmail.com using array_map
function registered_users(){ $file_user = file('userdata.php'); return array_map(function($user){ return explode(':',$user); },$file_user); } //returns exploded array correctly. using foreach
function registered_users(){ $file_user = file('userdata.php'); foreach ($file_user $user) { return explode(':',$user); } }// returns array ( [0] => reme [1] => reme1991@jourrapide.com )
because array_map() iterates on elements in array.... foreach() same except return jumping out of on first iteration.
function registered_users(){ $users = []; $file_user = file('userdata.php'); foreach ($file_user $user) { $users[] = explode(':',$user); } return $users; } edit
in response question "why doesn't return array_map terminate iteration?"
because array_map() function loops/iterates every element in array, executing "callback" function against each element. return in "callback" function, acts on 1 individual array element @ time, , called multiple times array_map(), once each element of array in turn.
the return in "callback" returning modified value one individual element (the current element in array_map() loop) array_map() function.... it's telling array_map() new element value should be.
the array_map() function can't interrupted: continue iterating on next element, sending in turn "callback" function until has done every element in array.
Comments
Post a Comment