I have an indexed array that contains several associative arrays and I use simple
$my_arr = array_filter($my_arr, function($obj) {
return $obj["value"] < 100;
});
to filter some elements of the array.
This started to make Angular front end error in strange ways, so after a few minutes I found that it was being $my_arrconverted from an indexed array to an associative array.
- Is this expected behavior in
array_filter? - How can I say
array_filterthat I want an indexed array?
EDIT: as requested in the comments, mine $my_arr:
$my_arr = [
["foo" => "bar", "value" => 10],
["foo" => "var", "value" => 30],
["foo" => "car", "value" => 440],
["foo" => "dar", "value" => 700]
]
EDIT: A real world instance 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);
Conclusion:
{"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 Result:
{"photos":[{"foo":"bar","value":10},{"foo":"var","value":20},{"foo":"car","value":50}]}
{"photos":[{"foo":"var","value":20},{"foo":"car","value":50}]}