Loop through each value in the array and then use a switch statement on those values.
P粉513316221
2023-07-30 12:21:44
<p>I'm new to PHP and I was wondering if anyone could help me. </p><p>I have an array, the value in the array is determined by another function, but the value of the array is always "warning", "critical" or "ok", the length of the array can also be arbitrary . For example: </p><p><br /></p>
<p><code>$hold = array ( 'warning','warning','critical','ok');</code></p>
<p>How to use the switch function and the for loop function so that it loops through each value in the array and prints out the corresponding message (no matter how many times the message appears in the array, for example, a warning appears twice in the array, then the warning should be printed twice). </p><p>I tried the code below but it always prints unknown. </p><p><br /></p>
<pre class="brush:php;toolbar:false;">switch($hold){
case 'ok':
echo 'everything is ok';
break;
case 'warning':
echo 'it is a warning';
break;
case 'critical':
echo 'its critical';
break;
default:
echo 'unknown';
};</pre>
<p>Thank you</p>
Writing a switch statement requires quite a bit of code. Why not use another array to associate the message with the state in $hold? like this:
As you can see, I used a foreach() loop to iterate over $hold.
I used an associative array and the special Null coalescing operator. If you don't like this way you can use your switch statement.
For demonstration, please see: https://3v4l.org/jNkfF