Home > Software design >  Adding to array if value doesnt exist
Adding to array if value doesnt exist

Time:05-06

I have an array built from a log file and I want to create a new array containing only the player names.

$list[2] is the location of the player names

             if(preg_match_all('/^(.*?) Player "(.*)" (.*) /m', $open, $list))
                {
                     foreach($list[2] as $name)
                     {
                        if(!in_array($name,$players))
                        {
                         $players[] = ["Player"=>$name];
                        }
                     }
                 }
                var_dump($players);

Its adding the player names to the array however it is adding even if an entry exists with the name as a value.

** Answer ** Was resolved following suggested answer by using

  $gt = array_unique($list[2]);
    foreach($gt as $name)
     {
      $players[] = ["Player"=>$name];
     }

CodePudding user response:

You can use array_unique function https://www.php.net/manual/en/function.array-unique.php

             if(preg_match_all('/^(.*?) Player "(.*)" (.*) /m', $open, $list))
                {
                     foreach($list[2] as $name)
                     {
                         $players[] = ["Player"=>$name];
                     }
                 }
                $players=array_unique($players);
                var_dump($players);

other solution:

             if(preg_match_all('/^(.*?) Player "(.*)" (.*) /m', $open, $list))
                {
                     foreach($list[2] as $name)
                     {
                        if(!in_array(["Player"=>$name],$players))
                        {
                         $players[] = ["Player"=>$name];
                        }
                     }
                 }
                $players=array_unique($players);
                var_dump($players);
  • Related