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
- GET_id not working in UnLink (delete file)
PHP - MySQL
First post
I searching for an hour for a solution; unlink seems not to work with GET id
<?php
$id = (int) $_GET ;
echo $_GET ;
$file = fopen( '.$_GET...
Last post
Here is an answer `o god after 2 hours shame on me for this one`
<?php
$file_pointer = $_GET .'.txt';
if (!unlink($file_pointer)) {
echo (...