2

I use the following code to conditionally remove items from an array:

$fruits = ['apple', 'orange', 'melon', 'banana', 'pineapple'];

echo json_encode($fruits) ."<br>";

foreach ($fruits as $key=>$fruit) {
    if (in_array($fruit, ['apple', 'orange', 'melon', 'banana'])) {
        unset($fruits[$key]);
    }
}

echo json_encode($fruits) ."<br>";

Now the problem is that the unset changes the array to an associative array. How should I remove items without causing this?

Output:

["apple","orange","melon","banana","pineapple"]
{"4":"pineapple"}
1
  • 1
    I don't think anything changed, you just created a hole in your array and so the display function now explicitly prints out the index since some are missing. Commented Mar 24, 2020 at 12:08

1 Answer 1

4

Your issue is that whenever json_encode finds an array which does not have consecutive numeric keys starting at 0, it has to represent it as an object with numeric keys to get an accurate representation of the array in JavaScript (see Example #4 on the manual page). You can work around this by running the array through array_values to re-index it to 0. For example:

$array = array('a', 'b', 'c');
echo json_encode($array, JSON_PRETTY_PRINT) . "\n";
unset($array[1]);
echo json_encode($array, JSON_PRETTY_PRINT) . "\n";
$array = array_values($array);
echo json_encode($array, JSON_PRETTY_PRINT) . "\n";

Output:

[
    "a",
    "b",
    "c"
]
{
    "0": "a",
    "2": "c"
}
[
    "a",
    "c"
]

In your case, after the foreach loop, you would use

$fruits = array_values($fruits);

to reset the indexes in that array.

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.