Delete an element from an array in PHP

To delete an element from an array in PHP, you can use any of the PHP built-in functions like unset(), array_splice(), or array_diff()

Using PHP unset() function

The unset() is an in-built function in PHP used to unset/destroy a given variable or an element from an associative array and numeric array. The below example shows how to delete an element from an array.

// unset used in numeric array
$products = ['Phone', 'laptop', 'watch'];
unset($products[1]);
print_r($products);
// Output: Array ( [0] => Phone [2] => watch ) 


// unset used in associative array
$person = ['name'=>'John', 'age'=>25, 'job'=>'Developer'];
unset($person['age']);
print_r($person);
// output: Array ( [name] => John [job] => Developer )

The unset function destroys the given element and it won't return anything.

In the example, can see that after unset, the index of the numeric array is not changed. That means re-indexing is not happening in the unset function. If you want to reindex the keys you can use array_values() after unset like this.

$products = ['Phone', 'laptop', 'watch'];
unset($products[1]);
$products = array_values($products);
print_r($products);
// output: Array ( [0] => Phone [1] => watch ) 

Using PHP array_splice() function

The array_splice() method removes a portion from an array and can be replaced with new elements if needed. Our scenario is to remove an element from an array. So we are passing only the index of the removing portion and length.

$products = ['Phone', 'laptop', 'watch'];
array_splice($products, 1, 1);
print_r($products);
// output: Array ( [0] => Phone [1] => watch )

The array_splice method will re-index the given array after removing the element.

Using PHP array_diff() function

If you want to delete multiple elements from an array in PHP, you can use array_diff() function instead of calling  unset() multiple times. 

$products = ['Phone', 'laptop', 'watch', 'pen', 'books'];
$result = array_diff($products, ['laptop', 'pen']);
print_r($result);
// output: Array ( [0] => Phone [2] => watch [4] => books )

The array_diff() compares an array against another array and returns the values in the first array which are not present in the second array. When using array_diff, The resulting array will not be re-indexed. If you want to re-index, use array_values() after array_diff().

$products = ['Phone', 'laptop', 'watch', 'pen', 'books'];
$result = array_diff($products, ['laptop', 'pen']);
$reindexed = array_values($result);
print_r($reindexed);
// output: Array ( [0] => Phone [1] => watch [2] => books )

Conclusion

To delete an element from an array in PHP, use PHP built-in functions like unset(), array_splice(), or array_diff(). The unset() unset function destroys the given element and the result array will not be reindexed. The array_splice() function removes a portion of the array and the result array will be reindexed. The array_diff() method can be used to remove multiple elements from an array.

Related Blogs

Create Multiple Where Clause Query Using Laravel Eloquent

How to create multiple where clause query using Laravel eloquent

Multiple where clauses can create by chaining the where() method. You can use orWhere, whereNot, etc to create complex where queries in Laravel Eloquent.

laravel sort by pivot table field

Laravel Order by Pivot Table Field

Learn how to order results by pivot table field in eloquent. Two methods 1) using orderBy in Eager loading 2) Using orderByPivot in lazy loading

Limit Text in Laravel

Limit Text in Laravel

Limit text in Laravel can be done using the Str class from Illuminate\Support\Str namespace for truncating text by character count and word count.

419 page expired Laravel error

419 page expired error in Laravel

419 page expired error in Laravel occurs when the valid CSRF token is missing in the post request. Laravel checks the CSRF token in VerifyCsrfToken middleware.

What's New in PHP 8

What's New in PHP 8(Features, Changes, Security & JIT compiler)

PHP 8 new features and functions include named arguments, union types, attributes, constructor property promotion, match expression, nullsafe operator, Saner string to number comparisons, Saner Numeric Strings, and JIT Compiler.

Regular Expression

Most Common Regular Expressions - email, URL, strong password, credit cards, number systems and dates

Regular expressions for email, URL, strong password, credit cards, number systems, dates and more.

Can't Perform a React State Update on an Unmounted Component

Can't Perform a React State Update on an Unmounted Component

React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted. Explains how to fix it.

Each child in a list should have a unique key prop

Each child in a list should have a unique key prop

Solve Warning: Each child in a list should have a unique ”key" prop in React by setting the id property as a unique key or by auto-assigning unique keys.

React Hook is Called Conditionally

React Hook is Called Conditionally

Error: "React Hook is called conditionally. React Hooks must be called in the exact same order in every component render" occurs when hooks are invoked conditionally or after a return of a value.