1

So i tried to loop through bunch of arrays using the while loop. So it does not work like this, how does it work?

    while($x<$sQuery($SERVER)['number'])
    {
        $o = $o . "<Server>
      <Name>".$sQuery($SERVER)[$x]['name']."</Name>
      <DNS>".$sQuery($SERVER)[$x]['ip']."</DNS>
    <Lat>0</Lat>
      <Long>0</Long>
      <Usage>-1</Usage>
      <RankRequired>0</RankRequired>
    </Server>"
        x++;
    }
}

The error is in this line(s):

      <Name>".$sQuery($SERVER)[$x]['name']."</Name>
      <DNS>".$sQuery($SERVER)[$x]['ip']."</DNS>

The [$x] is not allowed and i do not know how i can loop through them, any ideas?

4
  • 1
    x++; need to be $x++; Also ; missed too Commented Sep 2, 2016 at 20:28
  • where's the semicolon after the </Server>" ? also, what is "x++"; ? maybe $x++; ? Commented Sep 2, 2016 at 20:28
  • I don't recomment using $sQuery($SERVER). This is running that function over and over, every iteration. Better do it once before the loop and just use it statically. Commented Sep 2, 2016 at 20:31
  • What version of PHP are you running? You need to be running PHP 5.4 or later to use an index after a function call. See stackoverflow.com/questions/10767976/… Commented Sep 2, 2016 at 20:40

2 Answers 2

1

I would rewrite it this way:-

$s = $sQuery($SERVER);

for($i=0; $i<$s['number']; $i++)
{
    $o .= "<Server><Name>".$s[$i]['name']."</Name>
           <DNS>".$s[$i]['ip']."</DNS><Lat>0</Lat><Long>0</Long><Usage>-1</Usage>
           <RankRequired>0</RankRequired></Server>";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why not use foreach?
@Barmar Because there are the elements he needs AND the ["number"] element on the same level. You can go with foreach but you will have to ignore the "number" key then, an extra line.
1

So, I'm answering my own question (kinda). The comments helped me a lot. The thing is.. i should go to sleep because i am too tired for programming.

function ListServersXML($SERVER)
{
    $x = 0;
    $o = "";
    $s = sQuery($SERVER);
    while($x<$s['number'])
    {
        $o = $o . "<Server>
      <Name>".$s[$x]['name']."</Name>
      <DNS>".$s[$x]['ip']."</DNS>
    <Lat>0</Lat>
      <Long>0</Long>
      <Usage>-1</Usage>
      <RankRequired>0</RankRequired>
    </Server>";
        $x++;
    }
    return $o;
}

(btw this is my full function)

3 Comments

it's your responsibility to provide full code. It's not a good practice to hide code and then answer your question itself by showing full code (while others comment and answer resolved your problem)
Why don't you want to use foreach?
@Barmar as I already said, he has the elements he needs AND the ["number"] element on the same level. You can go with foreach but you will have to ignore the "number" key then, an extra line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.