Access array by its numeric index

I have this array

Array ( [name] => guardian [url] => http://www.guardian.co.uk )
Array ( [name] => cnn [url] => http://www.cnn.com )

which i am accessing like

$das_repeat = get_post_meta($post->ID, 'repeatable_fields', true);
    foreach ( $das_repeat as $fiel ) {
    echo $fiel['name'].'<br/>';
    //print_r($fiel);
    }

However, i am very interested in accessing each value by its numeric index.How can i reindex $fiel['name'] to allow me access each value by its index?.

Upvotes: 0

Views: 58

Answers (5)

Vlad Preda
Vlad Preda

Reputation: 9920

To re-index an array you can use array_values.

$array = array(
    'name' => 'A name',
    'attr2' => 'Attr 2'
);
$array = array_values($array);
var_dump($array);

Result:

array
  0 => string 'A name' (length = 6)
  1 => string 'Attr 2' (length = 6)

Although, as @deceze pointed out, this has the potential to cause bugs and/or unexpected behavior in your code, so use wisely. For example, think about what will happen if, for some reason, the 1st post meta will be deleted. All the information you show will be wrong.

Note: Is not recursive

Upvotes: 1

Barmar
Barmar

Reputation: 781814

As other answers say, you can use array_values to create a new array with the same values, but numeric indices. If you want to keep the associative array as it is, but also access it numerically, you could do this:

$keys = array_keys($das_repeat);
$elementN = $das_repeat[$keys[$N]];

Upvotes: 0

Ignas
Ignas

Reputation: 1965

Use array_values.

foreach ( $das_repeat as $fiel ) {
    $field = array_values($fiel);
    echo $field[0]; //will output guardian and then cnn
}

Upvotes: 0

exussum
exussum

Reputation: 18558

foreach ( $das_repeat as $id => $fiel ) {
    echo $fiel['name'].'<br/>';
    //print_r($fiel);
    // $id not contains the index
    }

Upvotes: 0

deceze
deceze

Reputation: 522442

Your array does not have numeric indices, it does not really make sense to access it by numeric indices. You can strip all the keys out and reindex the array numerically:

$reindexed = array_values($das_repeat);

However, again, it doesn't really make sense to do so. If you want to iterate over the array without knowing its keys, you're already doing that using foreach.

Upvotes: 2

Related Questions