Reputation: 10880
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?
Upvotes: 2
Views: 235
Reputation: 47854
If you like a fully functional-style approach: chunk, transpose, combine. Demo
var_export(
array_combine(...array_map(null, ...array_chunk($array, 2)))
);
Or chunk and use array destructuring syntax inside of body-less loop to push associative elements into a result array. Demo
$result = [];
foreach (array_chunk($array, 2) as [$k, $result[$k]]);
var_export($result);
Output:
array (
'english' => 85,
'mathematics' => 75,
'science' => 71,
'social' => 92,
)
Upvotes: 0
Reputation: 17577
In functional style just for the kick (not considering performance):
$odd = function($value) {
return($value & 1);
};
$even = function($value) {
return(!($value & 1));
};
$oddArr = array_filter($arr, $odd));
$evenArr = array_filter($arr, $even));
$ans = array_combine($oddArr,$evenArr);
Upvotes: 0
Reputation: 17577
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];
}
Upvotes: 0
Reputation: 625007
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.
Upvotes: 3
Reputation: 454920
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)
}
Upvotes: 2