TAS
TAS

Reputation: 331

php function gives unexpected output

I'm trying to count the word "online" in an array with keys and values.

function p($a){
    function printAllVals($a, $val) {
      if (!is_array($a)) {
        if ($a == "online"){
            $val+=1;
            echo $val;
            //echo $a  <-- this prints online 5 times
        }
          return;
       }
       foreach($a as $k => $v) {   
           printAllVals($v, $val);
       }  
    }
    printAllVals($a, 0);
}

it prints "online" 5 times when echoed $a, but when the $val prints "1" 5 times. Seems like it's taking the original value of $val when the function is called. What have I done wrong?

$a is the array and it's like the following(multi dimensional):

prod:
        cluster:
            csddb:
                inst_1: online
                inst_2: online
            oiddb:
                inst1: online
                inst2: offline
        local:
            quoid:
                inst_1: offline
                inst_2: offline
            qaprod:
                inst_1: offline
                inst_2: offline

Sorry for the incomplete question.

Upvotes: 0

Views: 45

Answers (1)

nospor
nospor

Reputation: 4220

This is recursion. So when recursion back to previous state it also backs to previous values so you loose state of $val; You must just return $val:

    function printAllVals($a, $val) {
      if (!is_array($a)) {
        if ($a == "online"){
            $val+=1;
            echo $val;
//            echo $a;
        }
          return $val;
       }
       foreach($a as $k => $v) {   
           $val = printAllVals($v, $val);
       } 
       return $val;
    }
    printAllVals($a, 0);

Upvotes: 0

Related Questions