Kitson88 Kitson88 - 1 month ago 14
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

$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


}

Answer

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