126

I would like to convert the array:

Array ( 
[category] => category 
[post_tag] => post_tag 
[nav_menu] => nav_menu 
[link_category] => link_category 
[post_format] => post_format 
)

to

array(category, post_tag, nav_menu, link_category, post_format)

I tried

$myarray = 'array('. implode(', ',get_taxonomies('','names')) .')';

which echos out:

array(category, post_tag, nav_menu, link_category, post_format)

So I can do

echo $myarray;
echo 'array(category, post_tag, nav_menu, link_category, post_format)';

and it prints the exact same thing.

...but I can't use $myarray in a function in place of the manually entered array because the function doesn't see it as array or something.

What am I missing here?

2
  • It won't work anywhere because you're passing a string, not an actual array. see @redreggae's answer for how to get just the values. Commented Mar 3, 2013 at 22:55
  • Possible duplicate of associative to numeric array in PHP Commented Feb 12, 2016 at 16:16

3 Answers 3

264

simply use array_values function:

$array = array_values($array);
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't this still store it as an associative array but just has indexes?
I think the term associative array is only for named keys. In this case it's an indexed array.
17

You should use the array_values() function.

1 Comment

Yeah, that was it. I was trying it befoere but I must have been doing something wrong. Here's the final function I ended up using... get_terms( array_values((get_taxonomies('','names'))) , $args )
5

create a new array, use a foreach loop in PHP to copy all the values from associative array into a simple array

      $data=Array(); //associative array

      $simple_array = array(); //simple array

      foreach($data as $d)
      {
            $simple_array[]=$d['value_name'];   
      }

1 Comment

This could be done in one line with array_column, like this $simple_array = array_column($data, 'value_name')

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.