-3

How do I get the value of an associative array using its key. For example, I have:

$new = array(

array(
"post" => "anything",
"newt" => "Nothing"
),
array(
"post" => "something",
"newt" => "Filthy"
),
    array(
"post" => "one value",
"newt" => "normal"
),
    array(
"post" => "two value",
"newt" => "happy"
),
    array(
"post" => "Three",
"newt" => "more"
)
);

Now I want to get the value of post. That means I want to get echoed anything, something. How do I accomplish this? I tried a way but that's not working. Example;

print_r($new['post']);

I also tried echo $new['post']; but doesn't work. Please help

user3293145
  • 193
  • 1
  • 10
  • `echo $new[0]['post'];` (returns:anything) and `echo $new[1]['post'];` (returns:something) –  Apr 14 '14 at 22:21
  • What if I want both the values? – user3293145 Apr 14 '14 at 22:21
  • that is both the values (anything, something) –  Apr 14 '14 at 22:21
  • 3
    This question appears to be off-topic because it shows no prior research nor minimal understanding of the problem being solved – Marcin Orlowski Apr 14 '14 at 22:22
  • @Dagon I mean by one line of code either `print` or `echo` instead of two echoes – user3293145 Apr 14 '14 at 22:23
  • possible duplicate of [php: how to get indexed array of key values](http://stackoverflow.com/questions/21657456/php-how-to-get-indexed-array-of-key-values) – Populus Apr 14 '14 at 22:23
  • `echo $new[0]['post'].' '.$new[1]['post'];` sorry this is really *basic syntax* stuff you should learn –  Apr 14 '14 at 22:24
  • @Dagon Sorry I have edited my question. Is there a way to get all values at once rather than doing `echo $new[0]['post']` and 1,2,3 and so on. I mean something like `print_r($new['post'])` and it would print `value1,value2,value3,value4` – user3293145 Apr 14 '14 at 22:30
  • @user3293145 see answer below –  Apr 14 '14 at 22:30

3 Answers3

1

after the edit i guess you want more than 2 ?

so ..

foreach ($new as $n){
echo $n['post'].',';
}
Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
1

You can do like this

foreach($new as $key => $value){
  echo $value['post']."<br/>"; 
}

Incase you don't need the key:

foreach($new as $value){
  echo $value['post']."<br/>"; 
}

Live Demo...

Krimson
  • 7,386
  • 11
  • 60
  • 97
1

PHP >= 5.5.0

foreach(array_column($new, 'post') as $post) {
  echo $post;
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87