PHP

Remove value from array in PHP

Code

Deleting a value from an array by key in PHP is quite a simple task, but when it is necessary to delete an element of an array exactly by value, then there are slight difficulties. It seems to be a trivial task, but you have to use a little trick. In this article, we will look at how to delete an array element in PHP both by value and by key.

Remove value from array by key

Everything is very simple here. We need the PHP function unset (), which removes variables. With its help, you can also delete an array element by key. In the example below, we are removing the element with the key name from the $ array:

<?
$array = array('name' => 'Иван', 'lastname' => 'Иванов', 'site' => 'https://it-blog.ru');
unset($array['name']);
?>

As you can see, everything is quite simple, but how to remove an element from an array by its value, because the unset () function can find an element only by its key. You will learn more about this later.

Remove array element by value

To remove an element of an array by value, we will also use the unset () function, which removes elements by key, but first we will find an element by value. Another function array_search () will help us with this, which searches for an element by value and returns its key. Further, using the found key, we will remove the desired element from the array.

<?
$array = array('name' => 'Иван', 'lastname' => 'Иванов', 'site' => 'https://it-blog.ru');

if(($key = array_search('Иван', $array)) !== false){
     unset($array[$key]);
}
?>

As you can see, deleting an array element by value is quite simple, you just need to think a little.

You may also like...