Remove a string from an Array in PHP

This article, will discuss multiple ways to remove a string from an array in PHP.

Table Of Contents

Background

Suppose you have an array containing various city names like [“London”, “Paris”, “New York”, “Tokyo”], and you want to remove a specific city, say “Paris”. The aim is to modify the array so that it no longer includes “Paris”, resulting in [“London”, “New York”, “Tokyo”].

Solution 1: Using array_search() and unset()

A common approach to remove a specific string from an array in PHP involves using array_search() to find the key of the string and unset() to remove the element at that key.

Let’s see the complete example,

<?php
$cities = ["London", "Paris", "New York", "Tokyo"];
// Search for the key of the city to be removed
$key = array_search("Paris", $cities);

// Check if the city was found in the array
if ($key !== false) {
    // Remove the city from the array
    unset($cities[$key]);
}

// Display the modified array
print_r($cities);
?>

Output

Array
(
    [0] => London
    [2] => New York
    [3] => Tokyo
)

In this code, array_search(“Paris”, $cities) locates the key of “Paris” in the $cities array. If found, unset($cities[$key]) is used to remove “Paris” from the array.

Solution 2: Using array_diff()

Alternatively, array_diff() can be used to create a new array that contains all elements of the original array except the specified string.

Let’s see the complete example,

<?php
$cities = ["London", "Paris", "New York", "Tokyo"];
// Remove the city from the array
$modifiedCities = array_diff($cities, ["Paris"]);

// Display the modified array
print_r($modifiedCities);
?>

Output

Array
(
    [0] => London
    [2] => New York
    [3] => Tokyo
)

Here, array_diff($cities, [“Paris”]) generates a new array that includes all elements of $cities except “Paris”. This method is particularly useful when removing multiple values or when you prefer not to modify the original array directly.

Summary

Removing a specific string from an array in PHP can be achieved using either array_search() with unset() for a targeted removal or array_diff() for a broader approach. Both methods are effective for manipulating arrays, especially in scenarios involving lists of data like city names, where you might need to exclude certain entries based on specific criteria.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top