2
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?

5
  • It's not clear what you're asking Commented May 28, 2017 at 11:20
  • Edited the question! Commented May 28, 2017 at 11:22
  • That would be $posts[ $i ]['username'] instead where $i is the index of the array inside the initial array. Commented May 28, 2017 at 11:23
  • I've edited it to make the structure clearer. You are duplicating the username inside each nested array. The value you try to access, $posts['username'][0] doesn't exist. I'd suggest you read more, like in the PHP docs before moving on. Commented May 28, 2017 at 11:29
  • Yeah that is what I should do! Thanks anyways! Commented May 28, 2017 at 11:30

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.