Why can't I access this array?

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Derbstep
New php-forum User
New php-forum User
Posts: 4
Joined: Wed Sep 26, 2012 3:46 pm

Why can't I access this array?

Postby Derbstep » Sat Oct 13, 2012 9:39 pm

Okay so I have my array.

Code: Select all

$_PAGE = array(
   'not_found' => array(
      'name' => 'not_found',
      'location' => 'page/notfound.php',
      'title' => 'Page Not Found'
   ),
   
   'home' => array(
      'name' => 'home',
      'location' => 'page/home.php',
      'title' => 'Home'
   ));

And I can access it fine using $_PAGE['not_found'], but when I try to access it with $_PAGE[0] it doesn't work, can I only choose to use numbers or words for my key?

I looked at this -> http://php.net/manual/en/function.array-keys.php and by looking at that my code should work but it just returns with an error.

Error:

Code: Select all

( ! ) Notice: Undefined offset: 0 in C:\www\include\script\function.php on line 35
Call Stack
#   Time   Memory   Function   Location
1   0.0002   672664   {main}( )   ..\home.php:0
2   0.0005   694392   do_header( )   ..\home.php:14


The code on line 35 is this

Code: Select all

echo $GLOBALS['_PAGE'][0]['title'];

The code works when I put $GLOBALS['_PAGE']['not_found']['title'].

How can I use the words as keys and still be able to access it using the numeric keys?

User avatar
simplypixie
php-forum Active User
php-forum Active User
Posts: 300
Joined: Sun Dec 11, 2011 12:51 am
Location: Shrewsbury, Shropshire
Contact:

Re: Why can't I access this array?

Postby simplypixie » Sat Oct 13, 2012 11:16 pm

As you have used names for your keys (i.e. 'not_found' => array....), you are replacing the numeric references to your array values and will only be able to access them using the string as the reference.

If you change it to:

Code: Select all

$_PAGE = array(
   array(
      'name' => 'not_found',
      'location' => 'page/notfound.php',
      'title' => 'Page Not Found'
   ),
   
   array(
      'name' => 'home',
      'location' => 'page/home.php',
      'title' => 'Home'
   ));


You can access using the numeric keys - try print_r($_PAGE) on the code above and your existing code and you will see the difference.

Derbstep
New php-forum User
New php-forum User
Posts: 4
Joined: Wed Sep 26, 2012 3:46 pm

Re: Why can't I access this array?

Postby Derbstep » Sun Oct 14, 2012 1:58 pm

Okay thank you. I just made another array to sort them accordingly.


Return to “PHP coding => General”

Who is online

Users browsing this forum: No registered users and 1 guest