J.Doe J.Doe - 2 months ago 6
PHP Question

Can't check string with foreach

I have got this php array

$Topic=[
'50 Cent' => '50cent.jpg Rap',
'Adam Levine' => 'adam.jpg Rock',
'Android' => 'android.jpg Operating System',
];


and this foreach code

<?php foreach ($Topic as $key => $value):
$type=substr($value,strpos($value,' '));
$value=explode(' ',$value);?>
<?php if (strcmp($type,'Rap')==0): ?>
<div class="topic_d">
<img src="topics/<?php echo $value[0]?>" class="topic_img">
</div>
<?php endif ?>
<?php endforeach ?>


My goal here is to print all topics in array that have got type 'Rap'.But i can't do that,even though when i print
type
it returns Rap/

Answer

Add trim to compare type with 'Rap'

if (strcmp(trim($type),'Rap')==0)

or to

$type=trim(substr($value,strpos($value,' '))); 

Because type is not 'Rap' but ' Rap'