How to find a value in an array and remove it by using PHP array functions?
Just in case you want to use any of mentioned codes, be aware that array_search
returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:
<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
unset($haystack[$key]);
}
var_dump($haystack);
The above example will output:
Array
(
[0] => one
[1] => two
[2] => three
)
And that's good!
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
You need to find the key of the array first, this can be done using array_search()
Once done, use the unset()
<?php
$array = array( 'apple', 'orange', 'pear' );
unset( $array[array_search( 'orange', $array )] );
?>
To search an element in an array, you can use array_search
function and to remove an element from an array you can use unset
function. Ex:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
print_r($hackers);
// Search
$pos = array_search('Linus Trovalds', $hackers);
// array_seearch returns false if an element is not found
// so we need to do a strict check here to make sure
if ($pos !== false) {
echo 'Linus Trovalds found at: ' . $pos;
// Remove from array
unset($hackers[$pos]);
}
print_r($hackers);
You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.