-1

//how can i get indexing number of this array without using any external varible

$ageRanges = ['name' => '17', 'min'=> null, 'max'=> '17'];

foreach($ageRanges as $key => $ageRange){printf($key);}
DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • Does this answer your question? [Convert associative array into indexed](https://stackoverflow.com/questions/7888847/convert-associative-array-into-indexed) – DarkBee Apr 14 '22 at 07:45
  • or keep track of the index through a variable that you are going to ++ at each iteration. But you should understand that such index won't be a key to the item in no way. The keys are not supposed to be ordered. – Diego D Apr 14 '22 at 07:46
  • I think the author asked to make it numerical without using external variables, and all the comments are suggesting using variables – mina.nsami Apr 14 '22 at 07:49
  • 1
    well actually it was me that got it totally wrong. Yes thanks for pointing out. My contribution was pretty out of topic – Diego D Apr 14 '22 at 07:50
  • @mina.nsami ` $value) { ... }` is not using any external variables imho – DarkBee Apr 14 '22 at 07:58
  • There can't be more than one key for elements in an array. You can use [array_values](https://www.php.net/manual/en/function.array-values.php) and get a new array with numeric indexes start with 0. Or you can take a counter to count the iteration ( not index ) – D Coder Apr 14 '22 at 08:00

2 Answers2

0

I don't understand why no variable should be used. If the task is like this, then the index can only be generated via array functions.

$ageRanges = ['name' => '17', 'min'=> null, 'max'=> '17'];
    
foreach($ageRanges as $key => $ageRange){
  echo array_search($key,array_values(array_keys($ageRanges)))  //index
    .": ".$key.' - '
    .var_export($ageRange,true)."\n";
}

Output:

0: name - '17'
1: min - NULL
2: max - '17'
jspit
  • 7,276
  • 1
  • 9
  • 17
-2

Your associative array here has string keys.

This is how associative arrays work in php, if you specify the key as you did, you don't get a numeric key.

if you did something like this:

$array = ['name', 'email', 'phone'];

The above has numeric keys.

So you can not achieve what yo want without using external variable.

The solution will be using external variable in your loop.

$ageRanges = ['name' => '17', 'min'=> null, 'max'=> '17'];

$index = 0;
foreach($ageRanges as $key => $ageRange){
    printf($index);
    printf($key);
    $index++;
}

mina.nsami
  • 411
  • 3
  • 7