Reputation: 175
I want to remove that 2 Justin Bieber
elements from this array and display it in select tag.
This is the code I have:
<?php
$arr = array('Dream Theater', 'Animals as Leaders', 'Chimp Spanner', 'Periphery', 'Linkin Park', 'Metallica', 'Justin Bieber', 'Slipknot', 'Justin Bieber');
echo "<pre>";
print_r($arr);
?>
<select>
<?php foreach ($arr as $value) {?>
<option><?php echo $value?></option> //I do not want to echo "Justin Bieber" here
<?php }?>
</select>
<?php
die;
Upvotes: 1
Views: 144
Reputation: 7485
<?php
$bands = ['Pink Floyd', 'The Animals', 'The Animals', 'TheThe', 'The Who', 'The Who'];
$counts = array_count_values($bands);
$repeats = array_filter($counts, function($v) { return $v>1;});
$filtered = array_diff($bands, array_keys($repeats));
?>
<select>
<?php foreach ($filtered as $value) { ?>
<option><?php echo $value?></option>
<?php }?>
</select>
Output:
<select>
<option>Pink Floyd</option>
<option>TheThe</option>
</select>
Upvotes: 1
Reputation: 37
Have you tried an if statement? Inside your foreach statement include :
if ($value!='justin bieber') {?>
//html code to be executed
<?php }?>
Upvotes: 3
Reputation: 23958
I believe you are looking for array_unique which will remove all duplicates from the array.
$arr = array('Dream Theater', 'Animals as Leaders', 'Chimp Spanner', 'Periphery', 'Linkin Park', 'Metallica', 'Justin Bieber', 'Slipknot', 'Justin Bieber');
$arr = array_unique($arr);
Now you only have one Justin Bieber.
To remove both Justin Bieber you can use array_diff.
This will return all values that is not "Justin Bieber" without looping.
$arr = array('Dream Theater', 'Animals as Leaders', 'Chimp Spanner', 'Periphery', 'Linkin Park', 'Metallica', 'Justin Bieber', 'Slipknot', 'Justin Bieber');
$arr = array_diff($arr, ["Justin Bieber"]);
To reindex the keys (if needed) use array_values.
Upvotes: 1
Reputation: 11642
You can do that with array-search (to find the string index) and unset
.
Consider the following:
$arr = array('Dream Theater', 'Animals as Leaders', 'Chimp Spanner', 'Periphery', 'Linkin Park', 'Metallica', 'Justin Bieber', 'Slipknot', 'Justin Bieber');
$v = 'Justin Bieber';
while ($key = array_search($v, $arr))
unset($arr[$key]);
Notice this will not fix your indexes (as you don't need to use them) but if you want them to be reset you can use $arr = array_values($arr);
Upvotes: 1