Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php How do you remove an array element in a foreach loop?

Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:

$result=array_search($unwantedValue,$array,true);
if($result !== false) {
  unset($array[$result]);   
}

The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.

Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:

$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
  unset($array[$key]);
}

Check http://php.net/manual/en/function.array-search.php for more information.
Comment

PREVIOUS NEXT
Code Example
Php :: Type cast using double php 
Php :: define in php 
Php :: laravel add crf token form 
Php :: fetch data from live website curl php 
Php :: php variable in string 
Php :: php remove array element 
Php :: Wordpress admin settings form 
Php :: php not recognized internal external command 
Php :: print only some characters of a string in php 
Php :: laravel 8 make model with migration and controller 
Php :: php global variable function 
Php :: What does "as" keyword mean in Laravel route ? 
Php :: call model function in controller laravel 
Php :: laravel sortby relationship column 
Php :: pagination with search query in laravel 
Php :: convert text file to json php 
Php :: php email attachment and message 
Php :: report simple error in php 
Php :: AUTO_INCREMENT in laravel 
Php :: php Calculate the number of months between two dates 
Php :: laravel tree category 
Php :: filter_var filter_validate_url 
Php :: get csv file from server folder in PHP 
Php :: autogenerate slug for model laravel 
Php :: htmlspecialchars (PHP 4, PHP 5, PHP 7, PHP 8) htmlspecialchars — Convert special characters to HTML entities 
Php :: rand string php 
Php :: how can we check in the table in comma separated values in laravel 
Php :: laravel 8 eloquent orderby 
Php :: wp query search 
Php :: php check if text is blank 
ADD CONTENT
Topic
Content
Source link
Name
9+7 =