php - Push only unique values into an array while looping

121

I am using the following loop to add items to an an array. I would like to know if it is somehow possible to not add$value to the$liste array if the value is already in the array?

$liste = array();
foreach($something as $value){
     array_push($liste, $value);
}
929

Answer

Solution:

Two options really.

Option 1: Check for each item and don't push if the item is there. Basically what you're asking for:

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

Option 2: Add them anyway and strip duplicates after:

foreach($something as $value) {
    array_push($liste,$value);
}
$liste = array_unique($liste);

By the look of it though, you may just be looking for$liste = array_unique($something);.

310

Answer

Solution:

As this question is using not the best practice code to begin with - I find all the answers here to be over-complicated.

Solving code in question:

Basically what is tried to do in question itself is filtering out repetitions. Better approach:

$liste = array_unique($something);

If adding elements to an array that is not empty:

$liste = array_unique(array_merge($liste, $something));

If you are using array_push():

Unless you are actually using return value of array push you should really use:

$liste[] = $value;

for shorter syntax and minor performance increase

458

Answer

Solution:

The right answer is much simpler. Push everything, but then usearray_unique() function:

array_push($array, $new_member);
$array = array_unique($array);
414

Answer

Solution:

maybe you want to use it as an associative array instead. it's implemented as (something like) a hash table, so you get constant insert time instead of linear.

function find_uniq( $something ) {
    foreach($something as $value){
         $liste[$value]++;
    }
    return array_keys( $liste );
}

If you want to suppress the warning, add the@ sign in line three.

If you want to avoid the warning, you need to check for existence first:

function find_uniq( $something ) {
    foreach($something as $value){
      if (isset($liste[$value]))
        $liste[$value]++;
      else
        $liste[$value] = 1;
    }
    return array_keys( $liste );
}
919

Answer

Solution:

You can simply check this condition before callingarray_push(). Usearray_search() and use a strong comparison tofalse to see if the value is present:

foreach( $something as $value ){
    if( array_search( $value, $liste, true ) === false ){
        array_push( $liste, $value );
    }
}

(By the way: Add,true toarray_search to use "strict checking". This will use=== for comparisons instead of==)

329

Answer

Solution:

I have another solution for you! You can use keys as values And keys will never be duplicated.

$arr = ["A" => true, "B" => true, "C" => true];

$item = "A";
$arr[$item] = true;

Usage:

foreach($arr as $value => $helper){
    echo $value;
}

Set class

OK, Let me write a class for you! The arrays do not allow duplicated items are called sets.

class Set{
    private $countainer;

    public function get(){
        return $this->container;
    }
    public function push($item){
        $this->container[$item] = true;
    }
    public function delete($item){
        unset($this->container[$item]);
    }
}

Note: This will not work for associative arrays and values.

833

Answer

Solution:

Great answers are already present above, but if you have multiple array_push() all over your code, it would be a pain to write if(in_array()) statements every time.

Here's a solution that will shorten your code for that case: Use a separate function.

function arr_inserter($arr,$add){ //to prevent duplicate when inserting
    if(!in_array($add,$arr))
        array_push($arr,$add);
    return $arr;
}

Then in all your array_push() needs, you can call that function above, like this:

$liste = array();
foreach($something as $value){
    $liste = arr_inserter($liste, $value);
}

If $value is already present, $liste remains untouched.

If $value is not yet present, it is added to $liste.

Hope that helps.

690

Answer

Solution:

Save logic and improve speed by keeping it logic-less. Just keep overwriting.

$list = array();
foreach ($something as $value) {
  if (!is_object($value) && !is_array($value)) {
    $list[$value] = $value
  }
}
$list = array_values($list);
57

Answer

Solution:

You can use values as temporary keys, so long as the$something array does not contain:

  1. non-scalar values (objects/arrays/etc. cannot be used as keys) or
  2. values that will be mutated when used as an array keys (floats get truncated, nulls become empty strings, and booleans become ints)
  3. a mix of numeric strings and integers that will be loosely evaluated as equal (2 vs"2")

(Bad Demo)


Code: (Good Demo)

$something = [3, 2, 1, 3, 6, 5, 1, 1];
$liste = [];
foreach ($something as $value) {
     $liste[$value] = $value;
}

Output:

array (
  3 => 3,
  2 => 2,
  1 => 1,
  6 => 6,
  5 => 5,
)

The above will absolutely perform better than any other approach on this page that is using a duplicate-checking technique. PHP will not allow duplicated keys on any single level of an array, so it will merely overwrite a re-encountered value.

If the new keys do not impact future processing, leave them as they are, otherwise callarray_values() to re-index the array.

People are also looking for solutions to the problem: php - Twig: How to set title in nested template blocks?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.