I have an indexed array that holds a few associative arrays and I apply a simple
$my_arr = array_filter($my_arr, function($obj) {
return $obj["value"] < 100;
});
function to filter some of the items in the array.
This started to make my Angular front end bug in weird ways, so after a few minutes I discovered that $my_arr
was being converted from an indexed array to an associative array.
array_filter
?array_filter
that I want an indexed array?EDIT: As requested in the comments, my $my_arr
:
$my_arr = [
["foo" => "bar", "value" => 10],
["foo" => "var", "value" => 30],
["foo" => "car", "value" => 440],
["foo" => "dar", "value" => 700]
]
EDIT: Real-world extract from my code:
$media = [
"photos" => [
["foo" => "bar", "value" => 10],
["foo" => "var", "value" => 20],
["foo" => "car", "value" => 50],
]
];
echo json_encode($media);
echo "\n\n";
$media["photos"] = array_filter($media["photos"], function($photo) {
return $photo["value"] > 15;
});
echo json_encode($media);
Output:
{"photos":[{"foo":"bar","value":10},{"foo":"var","value":20},{"foo":"car","value":50}]}
{"photos":{"1":{"foo":"var","value":20},"2":{"foo":"car","value":50}}}
Expected output:
{"photos":[{"foo":"bar","value":10},{"foo":"var","value":20},{"foo":"car","value":50}]}
{"photos":[{"foo":"var","value":20},{"foo":"car","value":50}]}
The array is not being converted from one type to the other - they're the same thing in PHP. It's just that array_filter()
is preserving the key/value associations when filtering. There is no way to automatically reindex the array according to the documentation, so you have to do it manually:
$my_arr = array_values(array_filter($my_arr, function($obj) {
return $obj["value"] < 100;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With