Dev Diaries WD logo Dev Diaries WD
PHP INTERVIEW · EP 07
PHP INTERVIEW · Episode 07

Find a value in an array — then remove it

in_array(), array_search(), unset() and friends

ep7_array_search_and_remove.php
<?php
$fruits = ["Apple", "Banana", "Mango", "Kiwi"];

$toRemove = "Mango";
if(in_array($toRemove , $fruits)){
    $elementPosition =  array_search($toRemove , $fruits);
    /* using unset and re searilize array
    unset($fruits[$elementPosition]);
    $fruits = array_values($fruits);
    */
    /* one line statement */
    array_splice($fruits,$elementPosition,1);
}else{
 // echo "value not found";
}
Output
Output for this tutorial goes here.

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Kiwi
)
        

Watch the full episode

Watch on YouTube