We help IT Professionals succeed at work.

New podcast episode! Our very own Community Manager, Rob Jurd, gives his insight on the value of an online community. Listen Now!


PHP and accessing Array Elements

AlexPonnath asked
Last Modified: 2017-05-15
I have some data thats returned in form of array and when i do a  print_r($LoginData); i get this

    [0] => Array
            [UserId] => acme
            [Password] => 123456
            [Spid] => 123L

    [1] => Array
            [UserId] => frank
            [Password] => Password
            [Spid] => 999E


Open in new window

$arrayLen = count($LoginData); comes back with 2 but then when i try
echo $LoginData[0][0].": Password: ".$LoginData[0][1].", Spid: ".$LoginData[0][2].".<br>";
echo $LoginData[0]['UserId'].": Password: ".$LoginData[0]['Password'].", Spid: ".$LoginData[0]['Spid'].".<br>";

Open in new window

i get the following error

<b>Notice</b>:  Undefined offset: 0 in <b>/var/www/html/Nanpa/dbTest.php</b> on line <b>23</b><br />
<br />
<b>Notice</b>:  Undefined offset: 1 in <b>/var/www/html/Nanpa/dbTest.php</b> on line <b>23</b><br />
<br />
<b>Notice</b>:  Undefined offset: 2 in <b>/var/www/html/Nanpa/dbTest.php</b> on line <b>23</b><br />
: Password: , Spid: .<br>
Watch Question

Fixer of Problems
Most Valuable Expert 2014
Unlock this solution and get a sample of our free trial.
(No credit card required)
Most Valuable Expert 2017
Distinguished Expert 2019

To expand on Dave's post

Take a look at the print_r output
Anything inside [ ] is an index - if you want to access that member you have to use the chain of index names to get there (as shown in the [ ])

What is the chain? In your example it starts with the variable that you used in the print_r - in this case $LoginData
Next we look at the first level of indexes - we can see from the output there are two elements in the topmost array indexed 0 and 1.
Each of these elements refers to another array indexed by UserId, Password and Spid.
Chain is therefore

$LoginData[0]['UserID'] for the first UserId
$LoginData[1]['Password'] for the second item's Password

Index values that are strings require quotes around them ['stringIndexValue'], numeric indexes do not require quotes BUT you can put quotes around them and they still work.
Most Valuable Expert 2011
Author of the Year 2014

Here's how quotation marks work in PHP.  This knowledge may be helpful when you're dealing with array indexes.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.