update page now

Voting

: min(nine, six)?
(Example: nine)

The Note You're Voting On

dassolucas at c238 dot com dot ar
1 year ago
The Problem:
---------------
When you filter an array in PHP using array_filter, the original keys are preserved. If you remove elements, you'll end up with gaps in the keys (non-consecutive). When encoded to JSON, this can lead to the list being interpreted as a JSON object instead of a JSON array, which might not be what your JavaScript code expects.
The Solution:
---------------
The array_values() function is essential in this scenario. It re-indexes the array with consecutive numerical keys (0, 1, 2, ...), ensuring that the JSON output is always a well-formed array.
Example:
----------
<?php
// Use Case: Filtering a list and ensuring consistent JSON array output
// Imagine you have a list of items and need to send a filtered version to a JavaScript frontend 
// using JSON. You want to ensure the filtered list is always received as a JSON array, 
// regardless of which items were removed.
// Sample data: A list of items
$items = [
 "first",
 "second",
 "third",
 "fourth",
 "fifth"
];
// Items to remove from the list
$itemsToRemove = ["second", "fourth"];
// Filter the list, keeping original keys (which become non-consecutive)
$filteredItems = array_filter($items, function($item) use ($itemsToRemove) {
 return !in_array($item, $itemsToRemove);
});
// Prepare data for JSON output
$output_arr = [
 "list" => $filteredItems 
];
// Output 1: JSON with non-consecutive keys (becomes an object)
echo "Output without array_values:\n";
echo json_encode($output_arr, JSON_PRETTY_PRINT) . "\n\n";
/* Output:
{
 "list": {
 "0": "first",
 "2": "third",
 "4": "fifth"
 }
}
*/
// Reset keys to be consecutive using array_values
$output_arr['list'] = array_values($output_arr['list']);
// Output 2: JSON with consecutive keys (remains an array)
echo "Output with array_values:\n";
echo json_encode($output_arr, JSON_PRETTY_PRINT) . "\n";
/* Output:
{
 "list": [
 "first",
 "third",
 "fifth"
 ]
}
*/
?>

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /