Kitson88 Kitson88 - 1 year ago 87
PHP Question

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

then use the array index as the case e.g.
. This works perfectly until it hits
. After the case matches
, it then assigns
and I cannot for the life of me understand why.

Input Array (7x Parameters):

$array = ['server1','','','This is server 01','1','1','1'];

Output of Foreach Loop (
after each case):

Name = Key: 0 & Value: server1
IP = Key: 1 & Value:
Host = Key: 2 & Value:
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


Answer Source

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: ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download