Link to home
Start Free TrialLog in
Avatar of AlexPonnath
AlexPonnathFlag for United States of America

asked on

PHP and accessing Array Elements

I have some data thats returned in form of array and when i do a  print_r($LoginData); i get this

Array
(
    [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>";
or 
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>
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Here's how quotation marks work in PHP.  This knowledge may be helpful when you're dealing with array indexes.
https://www.experts-exchange.com/articles/12241/Quotation-Marks-in-PHP.html