[php] 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?

This question is related to php arrays function built-in

The answer is


You can use array_filter to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.

You can use it like this:

$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');

And if you want to re-index the array, you can pass the result to array_values like this:

$output = array_values($output);

$data_arr = array('hello', 'developer', 'laravel' );


// We Have to remove Value "hello" from the array
// Check if the value is exists in the array

if (array_search('hello', $data_arr ) !== false) {
     
     $key = array_search('hello', $data_arr );
     
     unset( $data_arr[$key] );
}



# output:
// It will Return unsorted Indexed array
print( $data_arr )


// To Sort Array index use this
$data_arr = array_values( $data_arr );


// Now the array key is sorted

This solution is the combination of @Peter's solution for deleting multiple occurences and @chyno solution for removing first occurence. That's it what I'm using.

/**
 * @param array $haystack
 * @param mixed $value
 * @param bool $only_first
 * @return array
 */
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
    if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
    if (empty($haystack)) { return $haystack; }

    if ($only_first) { // remove the first found value
        if (($pos = array_search($needle, $haystack)) !== false) {
            unset($haystack[$pos]);
        }
    } else { // remove all occurences of 'needle'
        $haystack = array_diff($haystack, array($needle));
    }

    return $haystack;
}

Also have a look here: PHP array delete by value (not key)


The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)


<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>

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!


To find and remove multiple instance of value in an array, i have used the below code

$list = array(1,3,4,1,3,1,5,8);

$new_arr=array();

foreach($list as $value){

    if($value=='1')
    {
        continue;
    }
    else
    {
        $new_arr[]=$value;
    }     
}


print_r($new_arr);

First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-

<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>

Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-

<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>

Hope it helps.


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 )] );
?>

Okay, this is a bit longer, but does a couple of cool things.

I was trying to filter a list of emails but exclude certain domains and emails.

Script below will...

  1. Remove any records with a certain domain
  2. Remove any email with an exact value.

First you need an array with a list of emails and then you can add certain domains or individual email accounts to exclusion lists.

Then it will output a list of clean records at the end.

//list of domains to exclude
$excluded_domains = array(
    "domain1.com",
);

//list of emails to exclude
$excluded_emails = array(
    "[email protected]",
    "[email protected]",    
);

function get_domain($email) {

    $domain = explode("@", $email);
    $domain = $domain[1];
    return $domain;

}

//loop through list of emails
foreach($emails as $email) {

    //set false flag
    $exclude = false;

    //extract the domain from the email     
    $domain = get_domain($email);

    //check if the domain is in the exclude domains list
    if(in_array($domain, $excluded_domains)){
        $exclude = true;
    }

    //check if the domain is in the exclude emails list
    if(in_array($email, $excluded_emails)){
        $exclude = true;
    } 

    //if its not excluded add it to the final array
    if($exclude == false) {
        $clean_email_list[] = $email;
    }

    $count = $count + 1;
}

print_r($clean_email_list);

This is how I would do it:

$terms = array('BMW', 'Audi', 'Porsche', 'Honda');
// -- purge 'make' Porsche from terms --
if (!empty($terms)) {
    $pos = '';
    $pos = array_search('Porsche', $terms);
    if ($pos !== false) unset($terms[$pos]);
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to built-in

How to use the read command in Bash? What is the purpose of the : (colon) GNU Bash builtin? How to find a value in an array and remove it by using PHP array functions? What's the function like sum() but for multiplication? product()?