Kitson88
Kitson88

Reputation: 2940

Strange output when using a switch inside a foreach loop

I'm having a strange issue when assigning multiple array values to multiple properties using a switch inside a foreach loop. Basically my method above this loop takes an array as a parameter (working fine), I assign the switch parameter with the $array[$key] then use the array index as the case e.g. $array[0]. This works perfectly until it hits $array[4]. After the case matches $array[4], it then assigns $array[5] & $array[6] to $array[4] and I cannot for the life of me understand why.

Input Array (7x Parameters):

$array = ['server1','192.168.0.1','SERVER1.test.com','This is server 01','1','1','1'];

Output of Foreach Loop ($key,$value & echo after each case):

Name = Key: 0 & Value: server1
IP = Key: 1 & Value: 192.168.0.1
Host = Key: 2 & Value: SERVER1.test.com
Summary = Key: 3 & Value: This is server 01
CAT = Key: 4 & Value: 1
CAT = Key: 5 & Value: 1
CAT = Key: 6 & Value: 1

As you can see, CAT is outputted 3x but should only show once because the case does not match the Key

Code from Class:

 foreach ($array as $key=>$value) {

    switch ($array[$key]) {

        case $array[0]: $this->nodeName = $value; echo "Name = ";  break;
        case $array[1]: $this->nodeIP = $value; echo "IP = "; break;
        case $array[2]: $this->nodeHostname = $value;echo "Host = ";  break;
        case $array[3]: $this->nodeSummary = $value; echo "Summary = ";  break;
        case $array[4]: $this->nodeCategory = $value; echo "CAT = "; break;
        case $array[5]: $this->nodeSite = $value; echo "Site = "; break;
        case $array[6]: $this->nodeCompany = $value; echo "Company = "; break;
        case $array[7]: $this->nodePort = $value; break;
        case $array[8]: $this->nodeTime = $value; break;

    }

   echo "Key: " . $key . " & Value: " . $value . "<br>"; //For Diag


}

Edit (Since accepted answer)

DOH!

Upvotes: 2

Views: 208

Answers (3)

Ruben Bhattacharya
Ruben Bhattacharya

Reputation: 132

Array 4,5,6 values are same i.e 1.So case 1 is executed.

Upvotes: 0

Erik Kalkoken
Erik Kalkoken

Reputation: 32737

Here is why: I think you want to output each array element one by one, but your your case expressions use the value(!) of the array element. The values of $array[4], $array[5] and $array[6] are all 1. Since your case for [4] is the first one, its the only one that is triggered.

If my assumption is correct and you want to loop through all elements, try this instead:

switch ($key) {
 case 0: ...
 case 1: ...
}

Upvotes: 2

Anog
Anog

Reputation: 88

The switch/case matches $array[$key] with conditions IN THE ORDER you wrote them. This means that for key=5, you have $array[5] = 1 which happens to also be the value of $array[4], and as such the switch will trigger the [4] case and echo "CAT"

The same goes for 6.

Upvotes: 1

Related Questions