Loop through each value in the array and then use a switch statement on those values.
P粉513316221
P粉513316221 2023-07-30 12:21:44
0
1
693
<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>
P粉513316221
P粉513316221

reply all(1)
P粉295616170

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:

$hold = ['warning', 'warning', 'critical', 'ok', 'this is bad'];

$messages =  ['warning'  => 'it is a warning',
              'critical' => 'its critical', 
              'ok'       => 'everyhting is ok'];

foreach ($hold as $status) {
    echo ($messages[$status] ?? 'unknown') . PHP_EOL;
}

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!