im new to php and i was wondering if anyone could help me.
i have an array, the values in the array are determined by another function, but the array will always be either warning, critical or ok, the array can be any length as well.
for example:
$hold = array ( 'warning','warning','critical','ok');
how do i use a switch function and the forloop function, so that it loops through every value in the array and prints out the associative message (no matter how many times it appears in the array, for example warning appears twice in the array so the it is a warning should print twice).
i have tryed the code below, however it will always print out unknown.
switch($hold){
case 'ok':
echo 'everyhting is ok';
break;
case 'warning':
echo 'it is a warning';
break;
case 'critical':
echo 'its critical';
break;
default:
echo 'unknown';
};
thank you.
2
Answers
A switch statement takes quite a bit of code to write. Why not use another array to associate a message with a status in
$hold
. Like this:As you can see, I use a foreach () loop to go through
$hold
.I use an associative array and the special Null coalescing operator. You can use your switch statement if you don’t like this.
For a demo see: https://3v4l.org/jNkfF
You can perform a
switch
inside a loop, like this :foreach
seems easier to read than the classicfor
, but if you absolutely need it to be afor
, you can write it that way instead :Try this code here