2

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.

Community
  • 1
  • 1
Kevin Gagnon
  • 141
  • 11
  • No you can't declare a counter variable in the foreach construct. You could do it with a for-loop and just save the keys in an array, which you then can access with the counter variable. – Rizier123 Mar 10 '16 at 17:44
  • You mean accessing the number index in associatve array ? – Drudge Rajen Mar 10 '16 at 17:44
  • 1
    Also: foreach doesn't have its own scope. PHP has function scope and whatever you declare in foreach you can also use outside of it. – Rizier123 Mar 10 '16 at 17:45
  • @Drudge Yes, basically having a counter on the key when they are treated. Without having to declare a counter outside the scope that is incremented on each iteration. This has no goal, really, just curious if there was neat stuff to do with this – Kevin Gagnon Mar 10 '16 at 17:47
  • Possible duplicate of [How to find the foreach index](http://stackoverflow.com/questions/141108/how-to-find-the-foreach-index) – Don't Panic Mar 10 '16 at 17:49
  • @Rizier123 I think I just chose my words poorly, as English not being my first language. I meant "between the curly braces". As I understand now, "scope" is more definite than that. Like a class. Just a little misunderstanding on the word. – Kevin Gagnon Mar 10 '16 at 17:50
  • @KevinGagnon So you want a numeric index for your associative array inside the foreach loop, without defining or doing anything else outside of the foreach construct? (Which doesn't make much sense, unless it's a little coding challenge for you; Also see: http://stackoverflow.com/q/16959576/3933332 to see what exactly "variable scope" in PHP means) – Rizier123 Mar 10 '16 at 17:53
  • @Rizier123 Ahh on, like I mentioned it is only for fun and out of curiosity. Getting to know the language better, you know. – Kevin Gagnon Mar 10 '16 at 18:20
  • @Don'tPanic : My question is different than the one you linked. See my edit on why. – Kevin Gagnon Mar 10 '16 at 18:28

4 Answers4

4

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);
}
Ravindra Bhalothia
  • 1,720
  • 2
  • 13
  • 16
3

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>';
}
Drudge Rajen
  • 7,584
  • 4
  • 23
  • 43
  • 1
    This could work. I went with Ravindra's answer but this covers my question also. Thanks for your time :) – Kevin Gagnon Mar 10 '16 at 18:25
  • 1
    Great it works for you . :) . If this answer looks working for you, then please accept the answer so that it can be helpful to others as well. – Drudge Rajen Mar 10 '16 at 18:27
3

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";
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • That works if PHP iterates on an array in the same order that array_keys does. Which is a knowledge I do not have. Is there documentation on this that I could read ? This would become my favourite answer, as it serves the main purpose of the question and it saves CPU cycles. – Kevin Gagnon Mar 10 '16 at 18:46
  • I'm not sure I understand the question. `array_keys()` assigns the first key to index 0, the second to index 1, etc. `foreach()` resets the array pointer and starts at the first element of the array. The `$positions` array and `$myNamedIndexArray` will always match unless you modify them somehow. Plug any array into this and it works as expected. – AbraCadaver Mar 10 '16 at 18:50
  • http://stackoverflow.com/questions/4733188/is-foreach-guaranteed-to-iterate-in-the-array-order-in-php That cleared my understanding of foreach loop in PHP. I prefer your answer, thanks. – Kevin Gagnon Mar 10 '16 at 18:54
  • Also for some "light" reading: http://stackoverflow.com/questions/10057671/how-does-foreach-actually-work?rq=1 – AbraCadaver Mar 10 '16 at 18:56
  • Yes ! I actually had the tab openned already. Also, real quick, I am new to stackoverflow, would you have an idea of why my question had a downvote ? There is no question like mine and it was well constructed, I think. Is it because it doesn't serve a "real world job" purpose ? Thanks again. – Kevin Gagnon Mar 10 '16 at 18:59
2

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
Ed de Almeida
  • 3,675
  • 4
  • 25
  • 57
  • 1
    I received both Drudge's answer and yours at the same time and it is the same. That confirms it. Thanks for your time. – Kevin Gagnon Mar 10 '16 at 18:27
  • It happens. Sometimes we follow the same path, at the same time. The important is that the asnwers helped you. Thanks for the upvote. – Ed de Almeida Mar 10 '16 at 18:56