PHP - Delete array item by value (not key)

Discuss coding issues, and scripts related to PHP and MySQL.
MarPlo
Posts: 186

PHP - Delete array item by value (not key)

I have a PHP array as follows:

Code: Select all

$aray = array(312, 'string', 1599, 'other val');
$del_val = 1599; 
I want to delete the element containing the value $del_val, but I don't know its key. And each value can only be there once.

Admin Posts: 805
You can use array_search() and unset(), like in this example:

Code: Select all

$aray = array(312, 'string', 1599, 'other val');
$del_val = 1599;
if(($key = array_search($del_val, $aray)) !== false) {
  unset($aray[$key]);
} 
- array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset().

Or you can use the array_diff($ar1, $ar2) function, it returns the values in ar1 that are not present in $ar2. The second argument ($ar2) must be an array with the item you want to delete from $ar1.

Code: Select all

$aray = array(312, 'string', 1599, 'other val');
$aray = array_diff($aray, [1599]);

// test
var_export($aray);  // array(0=>312, 1=>'string', 3=>'other val') 

Similar Topics