I have an array
$users = array();
$users[0]['id']=1;
$users[0]['name']="user1";
$users[1]['id']=2;
$users[1]['name']="user2";
$users[2]['id']=3;
$users[2]['name']="user3";
And i need to extract id’s into another array $ids; such that
$ids[0]=1;
$ids[1]=2;
$ids[2]=3;
I know one way to do it…
$ids = array();
foreach($users as $user){
$ids[] = $user['id'];
}
But
1.is it is the best way to doit?
2.is it possible to do it without loops.
3.is it is the fastest way….?
All the comments above address the question very well, but since noone has actually posted any actual answer, here’s some additional info (to justify my answering it):
Probably, but it is certainly the cleaner and most readable way to do it
Yes, but as people have said, it’s only a trick, as loops will be used in the background.
Now this calls for some investigation. I have recreated a similar array as yours, using 100000 entries:
And ran a few tests using different cases:
1.Plain old for loop (the one you have used yourself):
This required 0.085” on average
2.Using array_walk():
This required on average 0.22” (the same when using $GLOBALS[‘ids’] instead of this “reference” hack)
3.Using splFixedArray:
This iterator is supposed to be faster than plain arrays. Indeed, the code above requires 0.075” on average:
While the code below, where we use splFixedArray for both arrays, performed even faster, around 0.062”:
So, the bottom line is that no, it’s not the fastest way, but it’s the best if you take into account all 3 parameters you posed in your initial question