Jordan Baron
Jordan Baron

Reputation: 4180

PHP illegal offset when trying to get value using a key

I am getting an illegal string offset error when trying to access the value of an array using a key.

define('SRV_INFO', array(
    'name' => 'Rustafied.com', 
    'info' => array(
        'ip' => '192.223.26.55:26032',
        'desc' => '350 slots of pure mayhem'
    ),

    'name' => 'Rustafied.com - Medium',
    'info' => array(
        'ip' => '74.91.122.115:28069',
        'desc' => 'The sweet spot between main and low pop'
    )
));

foreach(SRV_INFO as $server) {
                echo '
                <div class="server">
                    <span class="name">'. $server['name'] .'</span>
                    <span class="desc">'. $server['info']['desc'] .'</span>
                    <span class="pop"></span>
                </div>
                ';
            }

Upvotes: 0

Views: 20

Answers (1)

Joni
Joni

Reputation: 111269

With the way the rest of your code is written, the define should go like this:

define('SRV_INFO', array(
    array('name' => 'Rustafied.com', 
      'info' => array(
        'ip' => '192.223.26.55:26032',
        'desc' => '350 slots of pure mayhem'
    )),

    array('name' => 'Rustafied.com - Medium',
      'info' => array(
        'ip' => '74.91.122.115:28069',
        'desc' => 'The sweet spot between main and low pop'
    ))
));

If you did var_dump(SRV_INFO) with your current code you'd find that SRV_INFO is actually just the last entry you wrote:

php > var_dump(SRV_INFO);
array(2) {
  ["name"]=>
  string(22) "Rustafied.com - Medium"
  ["info"]=>
  array(2) {
    ["ip"]=>
    string(19) "74.91.122.115:28069"
    ["desc"]=>
    string(39) "The sweet spot between main and low pop"
  }
}

Upvotes: 2

Related Questions