Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array_push() -> How not to push if the array already contains the value

I am using the following loop to add items to an an array of mine called $liste. I would like to know if it is possible somehow not to add $value to the $liste array if the value is already in the array? Hope I am clear. Thank you in advance.

$liste = array(); foreach($something as $value){      array_push($liste, $value); } 
like image 242
Marc Avatar asked Apr 10 '12 20:04

Marc


People also ask

What does => mean in PHP array?

It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

How do you push a key and value in an array?

Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.

How do you check if value exists in array of objects PHP?

The function in_array() returns true if an item exists in an array. You can also use the function array_search() to get the key of a specific item in an array. In PHP 5.5 and later you can use array_column() in conjunction with array_search() .

What is difference between array push and pop in PHP?

In PHP, The array_push method can use to add or insert one or more items or elements from the end of an array. and The array_pop() method can use to extract, delete and remove the elements/items from the end of the array.


1 Answers

You check if it's there, using in_array, before pushing.

foreach($something as $value){     if(!in_array($value, $liste, true)){         array_push($liste, $value);     } } 

The ,true enables "strict checking". This compares elements using === instead of ==.

like image 113
Rocket Hazmat Avatar answered Sep 16 '22 15:09

Rocket Hazmat