phparraysfunctionbuilt-in

How to find a value in an array and remove it by using PHP array functions?


How to find if a value exists in an array and then remove it? After removing I need the sequential index order.

Are there any PHP built-in array functions for doing this?


Solution

  • 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.