Home > Software design >  PHP Creating an indexed array vs associative array
PHP Creating an indexed array vs associative array

Time:09-14

I am calling the getTeams function below to get a simple list of team names but I can't get it to work without a 2 step process. If I use

function getTeams($teams){
      
    foreach ($teams as $team) {
         $team = $team['team'];
         $teamNames[] = $team['displayName'];            
    }
    return $teamNames;      
} 

It looks like it is creating an associative array with the keys being numeric starting at 0?

I can make it work using

function getTeams($teams){
      
    foreach ($teams as $team) {
         $team = $team['team'];
         $teamNames[] = $team['displayName'];        
    }
    
    for ($i= 0; $i < count($teamNames); $i  ){
        $teamNames2[$teamNames[$i]]=$teamNames[$i]; 
    }
    return $teamNames2;
        
}

I think it might be because the first array is an associative Array and the second one is creating an indexed array? Is that thought process correct? If so, what is the correct way to create an indexed array in the foreach loop?

CodePudding user response:

Without knowing your array: If you want to create an associative array you should give its element a key. So instead of

function getTeams($teams){
      
    foreach ($teams as $team) {
         $team = $team['team'];
         $teamNames[] = $team['displayName'];            
    }
    return $teamNames;      
} 

where the code

$teamNames[]

will add always an indexed entry to your array.

If you want a associative entry use a key instead. Something like

function getTeams($teams){

    foreach ($teams as $team) {
         $team = $team['team'];
         $teamNames[$team['key']] = $team['displayName'];            
    }
    return $teamNames;      
} 

$teamNames should now return an associative array

  • Related