user967451
user967451

Reputation:

PHP: How to get an array's value by its numeric offset if it's an associative array?

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/
)

Upvotes: 5

Views: 4429

Answers (2)

prodigitalson
prodigitalson

Reputation: 60403

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

Upvotes: 0

nickb
nickb

Reputation: 59709

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.

Upvotes: 8

Related Questions