- How to find a value in an array and remove it by using PHP array functions?
- 11 Answers 11
- Perform Array Delete by Value Not Key in PHP
- Use the array_search() and unset() Function to Perform Array Delete by Value Not Key in PHP
- Syntax of array_search()
- Syntax of unset()
- Example of Removing Values From an Array in PHP
- Use the array_diff() Function to Perform Array Delete by Value Not Key in PHP
- Syntax
- Related Article — PHP Array
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?
11 Answers 11
Seems to be more efficient, the array $to_remove can be created using an array_search or preg_grep function in case if you are using wild card search to remove elements.
This solution is cleaner for me. However, note that it keeps indexes, so if you want to rearrange them in numerical order you’ll want to do this: array_values(array_diff($my_array, $to_remove))
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:
You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.
Also note that unset() will turn the array into an associative array. To turn it back into an array (without keys) use array_values()
To search by the value of a key you can combine this with array_column , ie: $pos = array_search(1234, array_column(‘id’, $dataset));
You need to find the key of the array first, this can be done using array_search()
This is the result Array ( [0] => apple [1] => orange [2] => pear [3] => green ) Warning: Wrong parameter count for array_search() in C:\wamp\www\test\test.php on line 5 Array ( [0] => apple [1] => orange [2] => pear [3] => green )
@learner the haystack argument was missing in de3.php.net/manual/en/function.array-search.php — the manual is your friend.
yes. this will work $array = array( ‘apple’, ‘orange’, ‘pear’, ‘green’ ); unset($array[array_search(‘orange’, $array)]); but the array sequence is missing. How to correct that
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:
The above example will output:
Array ( [0] => one [1] => two [2] => three )
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.
$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);
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; >
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)
Only if you don’t do a strict comparison for false . Algorhythm’s and chyno’s answers many years earlier do not make this mistake.
$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
First of all, as others mentioned, you will be using the «array_search()» & the «unset()» methodsas shown below:-
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:-
@algorhythm — Thanks for pointing that out! I will suggest that everyone should use the solution provided by you!
When you know that an answer is flawed and you leave ot on the page anyhow, you are only damaging the Researcher eXperience by confusing them with bad advice and/or wasting their time.
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.
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( "bob@domain2.com", "joe@domain3.com", ); 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);
Perform Array Delete by Value Not Key in PHP
- Use the array_search() and unset() Function to Perform Array Delete by Value Not Key in PHP
- Use the array_diff() Function to Perform Array Delete by Value Not Key in PHP
This article will introduce different methods to remove value from an array in PHP.
Use the array_search() and unset() Function to Perform Array Delete by Value Not Key in PHP
The main procedure to perform array delete by value, but not a key, is to find the value first. We could delete the value after it is found. We will find the value using array_search() function and delete it using unset() function. The unset() functions resets a variable. The correct syntax to use these functions is as follows.
Syntax of array_search()
array_search($value, $array, $strict);
The built-in function array_search() has three parameters. The details of its parameters are as follows
This function returns the key of the given value.
Syntax of unset()
unset($variable1, $variable2, . , $variableN);
The built-in function unset() has multiple parameters. The details of its parameters are as follows
This function returns nothing.
Example of Removing Values From an Array in PHP
The program below shows how we can use these functions to perform array delete by value, but not key, in PHP.
php $array = array("Rose","Lili","Jasmine","Hibiscus","Daffodil","Daisy"); echo("Array before deletion: \n"); var_dump($array); $value = "Jasmine"; if (($key = array_search($value, $array)) !== false) unset($array[$key]); > echo("Array after deletion: \n"); var_dump($array); ?>
Array before deletion: array(6) [0]=> string(4) "Rose" [1]=> string(4) "Lili" [2]=> string(7) "Jasmine" [3]=> string(8) "Hibiscus" [4]=> string(8) "Daffodil" [5]=> string(5) "Daisy" > Array after deletion: array(5) [0]=> string(4) "Rose" [1]=> string(4) "Lili" [3]=> string(8) "Hibiscus" [4]=> string(8) "Daffodil" [5]=> string(5) "Daisy" >
Use the array_diff() Function to Perform Array Delete by Value Not Key in PHP
In PHP, we can also use the array_diff() function to perform array delete by value not key. This function computes the difference of a given array with another array. The correct syntax to use this function is as follows.
Syntax
array_diff($array, $Arr1, $Arr2, . ,$ArrN);
The program that performs array delete by value, but not key, is as follows.
php $array = array("Rose","Lili","Jasmine","Hibiscus","Daffodil","Daisy"); echo("Array before deletion: \n"); var_dump($array); $value = array("Jasmine"); $array = array_diff( $array, $value); echo("Array after deletion: \n"); var_dump($array); ?>
Array before deletion: array(6) [0]=> string(4) "Rose" [1]=> string(4) "Lili" [2]=> string(7) "Jasmine" [3]=> string(8) "Hibiscus" [4]=> string(8) "Daffodil" [5]=> string(5) "Daisy" > Array after deletion: array(5) [0]=> string(4) "Rose" [1]=> string(4) "Lili" [3]=> string(8) "Hibiscus" [4]=> string(8) "Daffodil" [5]=> string(5) "Daisy" >
Related Article — PHP Array
Copyright © 2023. All right reserved