Chefk5
Chefk5

Reputation: 469

print out values from a php array

Array (
   [0] => Array ([username] => khaled [0] => khaled) 
   [1] => Array ([username] => Nariman [0] => Nariman) 
   [2] => Array ([username] => test1 [0] => test1) 
   [3] => Array ([username] => jack [0] => jack) 
   [4] => Array ([username] => mmmm [0] => mmmm) 
   [5] => Array ([username] => qqq [0] => qqq) 
   [6] => Array ([username] => wwwdwd [0] => wwwdwd) 
   [7] => Array ([username] => wddww [0] => wddww) 
   [8] => Array ([username] => maxa [0] => maxa) 
)

I tried $posts['username'][0]/[0]['username'] ... didnt work!

I want to print out some values of the array, like the username for example. How to do it?

Upvotes: 2

Views: 65

Answers (3)

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use the following solution using foreach:

foreach ($arr as $arrItem) {
    echo $arrItem['username'];
    echo $arrItem[0];
}

You can also use a for loop:

for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i]['username'];
    echo $arr[$i][0];
}

demo: https://ideone.com/he6h7r

Upvotes: 1

MinistryOfChaps
MinistryOfChaps

Reputation: 1484

To get a single variable (so your username in your case), you do the following:

$username = $posts[0]['username'];

This will get the username from the first nested Array in your actual array. You can modify this to get every username from each nested array by making a for loop so you get the rest of the usernames.

Upvotes: 2

Sakura Kinomoto
Sakura Kinomoto

Reputation: 1884

On you array, key ['username'] does not exist.

If you indent the array, they read as this:

Array
  [0]
    [username] => khaled
    [0] => khaled
  [1]
    [username] => Nariman
    [0] => Nariman
...

Because this, you can read $posts[0][0] or $posts[0][username], but, you cant read $posts[username] because didn't exist.

Upvotes: 1

Related Questions