Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_filter converting an indexed array to an associative array

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.

  • Is this the expected behavior in array_filter?
  • How can I tell 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}]}
like image 911
alexandernst Avatar asked Jul 25 '15 11:07

alexandernst


1 Answers

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;
}));
like image 199
Anonymous Avatar answered Sep 28 '22 02:09

Anonymous