Delete element from json with php

Delete element from json with php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Removing Elements from JSON in PHP

When you need to remove a specific record from a JSON file based on a matching property, your initial approach using a foreach loop is logically sound. However, simply iterating through an array does not automatically modify it; you must explicitly reconstruct the collection or manipulate its internal structure before re-encoding it to JSON.

In your example, you are trying to match $elemento['indirizzo_paginaauto'] against a URL provided via GET. Once you identify the element that matches, the goal is to exclude it from the final dataset. There are two primary strategies to achieve this: iterating with index access to build a new array, or using array functions to filter out the unwanted item.

Rebuilding the Array

The most explicit and readable method involves collecting the items you want to keep into a new array variable. This approach avoids modifying an array while iterating over it—a common source of bugs known as the "PHP modification during iteration" issue.

Here is how you can implement that logic within your loop:

$url = $_GET['indirizzo']; // Ensure this is sanitized and validated first
$data = json_decode(file_get_contents('autocaricate.json'), true);

// Check if data was decoded successfully
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new Exception('Invalid JSON in source file');
}

$newData = [];

foreach ($data as $elemento) {
    // We only skip the element if it matches the target URL
    // Using strict comparison is generally safer for strings
    if ($elemento['indirizzo_paginaauto'] !== $url) {
        $newData[] = $elemento;
    }
}

// Save the updated list back to the file
file_put_contents('autocaricate.json', json_encode($newData, JSON_PRETTY_PRINT));

In this snippet, we initialize an empty array $newData. Every element from the original $data that fails the if condition (meaning it is not the one to be deleted) gets appended to $newData. After the loop completes, we encode only $newData back to JSON. This ensures the matched item never enters the file system again.

Using array_filter for Conciseness

For a more functional programming style, you can utilize PHP's built-in array_filter() function. This allows you to define a callback that returns true for items to keep and false for items to discard.

$data = json_decode(file_get_contents('autocaricate.json'), true);

// The callback receives the current element ($item)
$filteredData = array_filter($data, function ($item) use ($url) {
    return $item['indirizzo_paginaauto'] !== $url;
});

// Reset keys to 0, 1, 2... because array_filter preserves original keys (e.g., 0, 5, 7)
// which might cause issues if your downstream logic relies on sequential indexing.
$filteredData = array_values($filteredData);

file_put_contents('autocaricate.json', json_encode($filteredData));

The array_values() step is critical here. If the original JSON had indices like 0, 1, 2, and you remove the item at index 1, array_filter will leave a "hole" (index 1 empty) or shift keys depending on the input type. Converting it back to a dense array ensures the resulting JSON is clean and sequential.

Important Considerations

Before writing code that alters data files, consider the source of truth. Is autocaricate.json a static snapshot or a cache? If this file represents your primary database, deleting a car record here implies you should also remove any associated files referenced by paths like indirizzo_immagine_copertina. Deleting the JSON entry without cleaning up the image directory will leave orphaned assets on your server.

Additionally, always validate the input $url. If the GET parameter is empty or malformed, attempting to match it against valid file paths could lead to unintended deletions or false negatives. Always sanitize inputs before using them in string comparisons.

If you are managing larger datasets or require more robust state management, consider moving away from flat JSON files and adopting an object-relational mapper (ORM) like Eloquent within the Laravel framework. This pattern allows you to handle data persistence with database transactions rather than manually parsing and rewriting text files.

Our network