I was trying to do some exercises in PHP for school and I ran into this...
My code:
<?php
$arr = [ 3, 4, 5, 6, "apple", 7.2, -10, "banana", 5, 5.1, 6, "okke" ];
$item = 0;
while ( $item < count($arr) ) {
echo $item." - ";
switch ( $item ) {
case $arr[ $item ] == 5:
echo $arr[ $item ]." --> This is 5<br />";
break;
case $arr[ $item ] == 6:
echo $arr[ $item ]." --> This is 6<br />";
break;
default:
echo " --> Not found<br />";
}
$item++;
}
?>
This is the result I get:
0 - 3 --> This is 5
1 - --> Not found
2 - 5 --> This is 5
3 - 6 --> This is 6
4 - --> Not found
5 - --> Not found
6 - --> Not found
7 - --> Not found
8 - 5 --> This is 5
9 - --> Not found
10 - 6 --> This is 6
11 - --> Not found
But in the first line I should get:
0 - --> Not found
Why is the Switch not working correctly??
You did the switch wrongly. :)
The switch ( $item ) { should contain item which you are searching for.
Fixed code here:
<?php
$arr = [ 3, 4, 5, 6, "apple", 7.2, -10, "banana", 5, 5.1, 6, "okke" ];
$item = 0;
while ( $item < count($arr) ) {
echo $item." - ";
echo $arr[$item];
switch ( $arr[ $item ] ) {
case 5:
echo $arr[ $item ]." --> This is 5<br />";
break;
case 6:
echo $arr[ $item ]." --> This is 6<br />";
break;
default:
echo " --> Not found<br />";
}
$item++;
}
?>
Or this would be another solution (not ideal one but I hope this would provide you more examples :)
<?php
$arr = [ 3, 4, 5, 6, "apple", 7.2, -10, "banana", 5, 5.1, 6, "okke" ];
$item = 0;
while ( $item < count($arr) ) {
echo $item." - ";
echo $arr[$item];
switch ( true ) {
case $arr[ $item ] === 5:
echo $arr[ $item ]." --> This is 5<br />";
break;
case $arr[ $item ] === 6:
echo $arr[ $item ]." --> This is 6<br />";
break;
default:
echo " --> Not found<br />";
}
$item++;
}
?>