Home > front end >  Associative Array in foreach with array-key and indexing number as well
Associative Array in foreach with array-key and indexing number as well

Time:04-14

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

CodePudding user response:

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'

CodePudding user response:

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  ;
}

  • Related