简体   繁体   中英

Get foreach numeric index when keys are named

This question is just for fun and out of curiosity.

Edit : My question is different than How to find the foreach index Because $key has already a non-numeric value in my case.

Without having a variable outside a foreach that is increment inside the foreach scope, as the usual $i, is there a way to get the index of an item when $key is already named ?

Exemples :

$myNumericIndexArray = ('foo', 'bar', 'go', 'habs');

foreach($myNumericIndexArray as $key => $value){
    //Here $key will be 0 -> 1 -> 2 -> 3
}

Now, if I have :

$myNamedIndexArray = ('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');

foreach($myNamedIndexArray as $key => $value){
    //Here $key will be foo -> go -> CSGO_bestTeam
}

Can I, without having to :

$i=0;
foreach($myNamedIndexArray as $key => $value){
    //Here $key will be foo -> go -> CSGO_bestTeam
    $i++;
}

access the index of a named array. Something declared in the foreach declaration like in a for or a status of $key ?

Have a good one.

If you really want index array of associative array than try this:

$myNamedIndexArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];

$keys = array_keys($myNamedIndexArray);
foreach($myNamedIndexArray as $key => $value){
     echo array_search($key, $keys);
}

Something like this :

<?php
$myNamedIndexArray = array('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
$numericIndexArray = array_keys($myNamedIndexArray);
foreach($numericIndexArray as $key=>$value){
    echo $key.'</br>'; //here key will be 0 1 2
    echo $value. '</br>';
}

I don't know why you would want to do an array_keys() and array_search() every loop iteration. Just build a reference array and you can still foreach() the original:

$positions = array_flip(array_keys($myNamedIndexArray));

foreach($myNamedIndexArray as $key => $value){
    echo "{$key} => {$value} is position {$positions[$key]}\n";
}

I'd try something like this:

<?php

    $myNamedIndexedArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];

    $myNumberIndexedArray = array_keys($myNamedIndexedArray);
    foreach($myNumberIndexedArray as $key => $value){
        echo $key. " => " . $myNamedIndexedArray[$myNumberIndexedArray[$key]]."<br />";
    }

?>

Adn the output will be:

0 => bar
1 => habs
2 => fnatic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM