5

I have an associative array which when var dumped looks like this:

Array
(
    [tumblr] => Array
        (
            [type] => tumblr
            [url] => http://tumblr.com/
        )

    [twitter] => Array
        (
            [type] => twitter
            [url] => https://twitter.com/
        )

)

As you can see the key's are custom "tumblr" and "twitter" and not numeric 0 and 1.

Some times I need to get the values by the custom keys and sometimes I need to get values by numeric keys.

Is there anyy way I can get $myarray[0] to output:

(
    [type] => tumblr
    [url] => http://tumblr.com/
)
3
  • Numeric and string keys are not interchangeable in PHP. Can you describe more what you need? Commented Jun 27, 2012 at 20:32
  • All arrays in PHP are associative, even the numerically indexed ones. This means that if you assign a string as the index, there is no associated numerical value. @nickb has a nice way to deal with this below. Commented Jun 27, 2012 at 20:34
  • @Michael don't even ask, working with someone else's code and don't feel like rewriting the whole thing. Commented Jun 27, 2012 at 20:37

2 Answers 2

8

You can run the array through array_values():

$myarray = array_values( $myarray);

Now your array looks like:

array(2) {
  [0]=>
  array(2) {
    ["type"]=>
    string(6) "tumblr"
    ["url"]=>
    string(18) "http://tumblr.com/"
  } ...

This is because array_values() will only grab the values from the array and reset / reorder / rekey the array as a numeric array.

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

1 Comment

$myarray+=array_values($myarray); would create an array that could use both named and numeric indexes, much the same way mysql_fetch_array works :)
0

You can use array_values to get a copy of the array with numeric indexes.

Comments

Your Answer

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