Removing Array Elements in PHP

Learn how to remove a specific item from an array with this helpful guide. Discover different methods for removing array elements in PHP, including using built-in functions like unset() and array_splice(), as well as more advanced techniques like filtering and mapping. Improve your PHP programming skills and streamline your array manipulations with these practical examples and tips.

Usually when working with arrays we are in need to remove a targeted element and execute a specific operation with it. In this post we’ll learn how to use the following function to remove an item by value from the designated array.

To remove a specific item from an array you need to traverse the array, check each value with the one you want to remove and then create a new array with all the other elements. The resulting array will not contain the designated item.

If you don’t know how to do that, I encourage you to use the function below. The remove function will even keep the indices as they are without changing each element’s position (or not), meaning that you can have a choice to remove an element and assign its value into a new position or keep the position in place for the record.

function remove($t, $v, $keep_index = false) {
    $ret_arr = array();
    foreach($t as $it)
        if ($keep_index==true){
            $ret_arr[] = ($it!=$v) ? $it : '';
        } else {
            if ($it!=$v){
                $ret_arr[] = $it;
            }
        }
    return $ret_arr;
}

$array = ['hello', 'world'];
print_r(remove($array, 'hello', true));
print_r(remove($array, 'world'));

There are several other ways to remove an item from an array in PHP. Some of the most commonly used methods include:

  1. Using the unset() function: This function removes a specific element from an array by unsetting its corresponding key. For example: unset($myArray[3]).
  2. Using the array_splice() function: This function removes one or more elements from an array and optionally replaces them with new values. For example: array_splice($myArray, 3, 1).
  3. Using the array_filter() function: This function filters an array based on a given condition and returns a new array without the filtered elements. For example: $newArray = array_filter($myArray, function($value) { return $value != 3; });.
  4. Using the array_diff() function: This function compares two arrays and returns the difference between them. For example: $newArray = array_diff($myArray, [3]);.

By using these methods, you can easily remove a specific element from an array in PHP according to your specific needs.