Search code examples
phparraysassociative-array

Convert a flat indexed array of alternating keys and values into a flat associative array


I have an array something like this:

[0] => english
[1] => 85
[2] => mathematics
[3] => 75
[4] => science
[5] => 71
[6] => social
[7] => 92

I want all values with even indexes to go as keys and all values odd indexes to go values. Like this:

[english] => 85,
[mathematics] => 75
[science] => 71
[social] => 92

Is there any good function to achieve this? or can you help me with the code?


Solution

  • A simple loop will do this:

    $input = array(
      'english',
      85,
      'mathematics',
      75,
      'science',
      71,
      'social',
      92,
    );
    $output = array();
    for ($i=0; $i<count($input); $i+=2) {
      $output[$input[$i]] = $input[$i+1];
    }
    print_r($output);
    

    Note: the above code assumes there are an even number of elements.