I want to copy elements of specific indices/keys from one php array to another. I came across this post and tried the following:
$a1=array(10,15,20,25,30);
$indices=array(2,4);
$result=array_intersect_key($a1,array_flip($indices));
print_r($result);
But my result is like this
Array ( [2] => 20 [4] => 30 )
I want the keys in the new array to start from [0]
. ie., I want the result to be
Array ( [0] => 20 [1] => 30 )
I looked at array_combine()
but is there any other efficient way to do this whole process.
Use array_values()
to get just the array values of the returned array from array_intersect_key()
.
$result=array_values(array_intersect_key($a1,array_flip($indices)));
If you have PHP5.3 or better, you could also use array_walk_recursive()
with a closure:
$array = [10,15,20,25,30];
$indices = [2, 4];
array_walk_recursive($array, function($value, $index) use(&$array, $indices)
{
if(!in_array($index, $indices))
unset($array[$index]);
});
return array_values($array);
Edit:
But is this more efficient than the previous solution?
Not really, no. Testing our original solutions, plus these two foreach solutions:
Foreach 1
function($array, $indices)
{
foreach($array as $key => $value)
if(!in_array($key, $indices))
unset($array[$key]);
return array_values($array);
}
Foreach 2
function($array, $indices)
{
$newArray = [];
foreach($indices as $index)
$newArray[] = $array[$index];
return $newArray;
}
I found the second foreach to be fastest: