user2703580
user2703580

Reputation: 11

Php print out value from array only once

well my code is this one and i want if the locationname is the same to be printed only once

$arr1 =$erster[0][$id[0]]['location'];

foreach ($arr1 AS $ref_key => $location2):
print $location2['locationname'] ;
endforeach;

Upvotes: 0

Views: 915

Answers (3)

user3227262
user3227262

Reputation: 583

You should instead make use of PHP built-in function array_unique(). Technically this function will only return the unique elements from the array.

$arr1 = $erster[0][$id[0]]['location'];
$newarray = array_unique($arr1);
print_r($newarray);

Upvotes: 1

user2703580
user2703580

Reputation: 11

I found a solution, I added an id and name field to my array and used

if($programm_location_id != $erster_programmpunkt[0][$id[0]]['location']['id']){
$programm_location_id = $erster_programmpunkt[0][$id[0]]['location']['id'];
$programm_location_name = $erster_programmpunkt[0][$id[0]]['location']['name'];
$programm_location_html = '<div class="span3">'.$programm_location_name.'</div>';

echo $programm_location_html;
}

thank you all

Upvotes: 0

voodoo417
voodoo417

Reputation: 12101

Do it:

$arr1 =$erster[0][$id[0]]['location'];

$repeats = array();
foreach ($arr1 AS $ref_key => $location2):
   $local_name = $location2['locationname'];

   if (!in_array($local_name,$repeats)){ // checking if $local_name is exists in "showed" array - $repeats
       print $local_name;                // if not - show $local_name             
       $repeats[] = $local_name;         // push  $local_name to "showed" array ( to $repeats)
   }

endforeach;

EDIT Another way . By comment @grebneke

$repeats = array();
foreach ($arr1 AS $ref_key => $location2):
$local_name = $location2['locationname'];

if (!array_key_exists($local_name,$repeats)){  // -//-
    print $local_name;                           
    $repeats[$local_name] = true;
}

endforeach;

Upvotes: 1

Related Questions