0

I've searched through the stack for an answer but it seems that I cannot find a solution for the following code:

$servers = array();
while($row = mysql_fetch_array( $result ))
{
   $servers[] = $row['name'] => array('ip' => $row['ip'],'port' => $row['port'],'info' => $row['info'],'purpose' => $row['purpose']),
}

What I'm trying to achieve is fetch all results but I receive the following error:

syntax error, unexpected '=>' (T_DOUBLE_ARROW).

Making it like this gets only the last item:

while($row = mysql_fetch_array( $result )) {
$servers = array(
    $row['name'] => array('ip' => $row['ip'],'port' => $row['port'],'info' => $row['info'],'purpose' => $row['purpose']),
    );
}

That being said, $servers is in the while loop, thus making it index only the last item. I don't know what causes the unexpected => :/

1

1 Answer 1

1

It looks like you're trying to do this:

$servers = [];
while($row = mysql_fetch_array( $result )) {
   $servers[$row['name']] =  [
       'ip' => $row['ip'],
       'port' => $row['port'],
       'info' => $row['info'],
       'purpose' => $row['purpose']
   ];
}

That gives you a final $servers array, indexed by server name, with an array of details.

Side note: as Jay commented, you really shouldn't be using mysql functions any longer, really encourage you to check out mysqli or PDO functions instead.

Sign up to request clarification or add additional context in comments.

3 Comments

seems like $servers = array(); did the job. $servers = []; was still calling only 1. I took note on Jay's comment and will take a deep look on it.
@MartinSpatovaliyski $servers = array() and $servers = [] are the exact same thing. [] is just shorthand for array().
@MartinSpatovaliyski If you'd like me to take a look at it, update your question with your modified code. something isn't right, and I can't tell you what's wrong unless I can see it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.