views:

84

answers:

3
+3  Q: 

Array Manipulation

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 ?

+2  A: 

Something like this:

<?php

$arr[0] = 'english';
$arr[1] = 85;
$arr[2] = 'mathematics';
$arr[3] = 75;
$arr[4] = 'science';
$arr[5] = 71;
$arr[6] = 'social';
$arr[7] = 92;

for($i=0;$i<count($arr);$i++)
{
        if($i & 1)
                $odd[] = $arr[$i];
        else
                $even[] = $arr[$i];
}

$result = array_combine($even,$odd);

var_dump($result);

?>

Output:

array(4) {
  ["english"]=>
  int(85)
  ["mathematics"]=>
  int(75)
  ["science"]=>
  int(71)
  ["social"]=>
  int(92)
}
codaddict
it will be better to use array_fetch_assoc to retrive the data using php...
Avinash
+3  A: 

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.

cletus
A: 

Solution using array_chunk function

$arr = array('english', 85,
         'mathematics', 75,
             'science', 71,
              'social', 92
);

$result = array();
$chunks = array_chunk($arr, 2);
foreach ($chunks as $value) {
  $result[$value[0]] = $value[1];
} 
Chandra Patni