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):
- Is it the best way to do it?
Probably, but it is certainly the cleaner and most readable way to do it
- is it possible to do it without loops?
Yes, but as people have said, it's only a trick, as loops will be used in the background.
- is it is the fastest way?
Now this calls for some investigation. I have recreated a similar array as yours, using 100000 entries:
for ($i=0;$i<100000;$i++) {
$users[] = array('id' => rand(),
'name' => 'default');
}
And ran a few tests using different cases:
1.Plain old for loop (the one you have used yourself):
$ids=array();
$t = microtime(true);
foreach ($users as $key => $value) {
$ids[] = $value['id'];
}
echo microtime(true)-$t;
This required 0.085'' on average
2.Using array_walk():
$t = microtime(true);
array_walk($users, create_function('$v,$k,&$ids', '$ids[0][] = $v["id"];'), array(&$ids));
echo microtime(true)-$t;
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:
$users = new SplFixedArray(100000);
for ($i=0;$i<100000;$i++) {
$users[$i] = array('id' => rand(),
'name' => 'default');
}
$ids=array();
$t = microtime(true);
foreach ($users as $key => $value) {
$ids[$key] = $value['id'];
}
echo microtime(true)-$t;
While the code below, where we use splFixedArray for both arrays, performed even faster, around 0.062'':
$users = new SplFixedArray(100000);
for ($i=0;$i<100000;$i++) {
$users[$i] = array('id' => rand(),
'name' => 'default');
}
$ids=new SplFixedArray(100000);
$t = microtime(true);
foreach ($users as $key => $value) {
$ids[$key] = $value['id'];
}
echo microtime(true)-$t;
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
array_walk()/array_map()etc - but this is just a loop in a different coat and in this case I suspect it would be less efficient than your simple, effective and easy to readforeach. So in short1.is it is the best way to doit?- probably, yes.2.is it possible to do it without loops.- definitely not, no. Even things that don't look like loops are just loops underneath (in the C++ source).3.is it is the fastest way....?- again, probably yes. I'd be surprised if it wasn't. But with something that will take <10usec, speed is not really a concern.1. No- care to expand? Or did you meanYes?