-3

I want to get some values from an array in PHP. I use print_r for debugging, and my array content is:

Array ( [54.38.202.159:20756] => Array ( [dedicated] => 1 [gamename] => mta [gametype] => MTA:SA [gq_address] => 54.38.202.159 [gq_dedicated] => 1 [gq_gametype] => MTA:SA [gq_hostname] => MTA @ ServerProject.eu [gq_joinlink] => mtasa://54.38.202.159:20756/ [gq_mapname] => None [gq_maxplayers] => 20 [gq_mod] => [gq_name] => Multi Theft Auto [gq_numplayers] => 0 [gq_online] => 1 [gq_password] => 1 [gq_port_client] => 20756 [gq_port_query] => 20879 [gq_protocol] => ase [gq_transport] => udp [gq_type] => mta [map] => None [max_players] => 20 [num_players] => 0 [password] => 1 [players] => Array ( ) [port] => 20756 [servername] => MTA @ ServerProject.eu [teams] => Array ( ) [version] => 1.5 ) )

How can I access some value from this array? For example, I want a "num_players" value. I was trying to use:

$data["num_players"]

But this gives me an error:

Notice: Undefined index: num_players

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FileEX
  • 65
  • 1
  • 11
  • 8
    It should be `$data['54.38.202.159:20756']['num_players']` – B001ᛦ May 31 '21 at 08:44
  • Follow the structure. `"num_players"` is not at the top level. `54.38.202.159:20756` is. A little tip for the future: use `var_dump` over `print_r`. It has more detailed information and display the structure in a more user-friendly way. – El_Vanja May 31 '21 at 08:44

1 Answers1

1

Your array is multidimensional, and the first dimension seems to be the IP address of the server.

If that IP address is fixed, you can use the answer of @B001ᛦ in the first comment to your question.

Otherwise, if it changes and if there can be multiple IP addresses, you can just loop.

foreach($data as $ip => $info) {
    echo $info['num_players'];
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrea Olivato
  • 2,450
  • 1
  • 18
  • 30