skip to Main Content

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


  1. 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:

    $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 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

    Login or Signup to reply.
  2. You can perform a switch inside a loop, like this :

    foreach ($hold as $message) {
        switch ($message) {
            case 'ok':
                echo 'everyhting is ok';
            break;
            case 'warning':
                echo 'it is a warning';
            break;
            case 'critical':
                echo 'its critical';
            break;
            default:
                echo 'unknown';
        }
    }
    

    foreach seems easier to read than the classic for, but if you absolutely need it to be a for, you can write it that way instead :

    for ($index = 0; $index < count($hold); $index++) {
        switch ($hold[$index]) {
            // Same code as before
        }
    }
    

    Try this code here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search