Assume the following array in PHP:
array('red','blue','green','purple');
I would like the simplest and fasted method to make that array come out like this:
array('red'=>'blue','green'=>'purple');
If there is a php function that already exists that does this, that would be even better. I'm running a php 5.4
and 5.5
both so there hopefully shouldn't be a problem.
Not necessarily the fastest approach, but perhaps it'll introduce a few people to some features of PHP that they weren't aware of before:
$isEven = function ($value) {
return !($value & 1);
};
$isOdd = function ($value) {
return $value & 1;
};
function keyfilter($values, $function) {
return array_intersect_key(
$values,
array_filter(
array_keys($values),
$function
)
);
}
$colourArray = array('red','blue','green','purple');
$mi = new MultipleIterator(
MultipleIterator::MIT_NEED_ANY |
MultipleIterator::MIT_KEYS_ASSOC
);
$mi->attachIterator(
new ArrayIterator(
keyfilter(
$colourArray, $isEven
)
),
'key'
);
$mi->attachIterator(
new ArrayIterator(
keyfilter(
$colourArray, $isOdd
)
),
'value'
);
$newColourArray = array();
foreach($mi as $details) {
$newColourArray[$details['key']] = $details['value'];
}
var_dump($newColourArray);
First thing that comes to my mind is something like this:
$array = array('red', 'blue', 'green', 'purple');
function array_pair($source)
{
$output = array();
do {
list($key, $value) = array_splice($source, 0, 2);
$output[$key] = $value;
} while (!empty($source));
return $output;
}
var_dump(array_pair($array));
Outputs an array just like you need it:
array(2) {
["red"]=>
string(4) "blue"
["green"]=>
string(6) "purple"
}
Will even work if you have an odd number of elements in your source array:
$array = array('red', 'blue', 'green', 'purple', 'odd');
var_dump(array_pair($array));
Results in:
array(3) {
["red"]=>
string(4) "blue"
["green"]=>
string(6) "purple"
["odd"]=>
NULL
}
You can easily write your own function to do this:
$src = array('red','blue','green','purple');
function glue($arr) {
while(count($arr) > 0) {
$dst[array_shift($arr)] = array_shift($arr);
}
return $dst;
}
foreach(glue($src) as $key => $value)
print $key ." => ".$value . "
";
$arr = array('red','blue','green','purple');
$result = array();
for($i = 0; $i < count($arr); $i++) {
if($i % 2 == 0) {
$result[$arr[$i]] = $arr[$i + 1];
}
}
output :
array (size=2)
'red' => string 'blue' (length=4)
'green' => string 'purple' (length=6)
$originalArray = array('red','blue','green','purple');
$compressedArray = array();
$count = 0;
while($count < count($originalArray))
$compressedArray[$originalArray[$count++]] =
$count < count($originalArray) ? $originalArray[$count++] : null;
print_r($compressedArray);
You can see it running on http://ideone.com/CTGXQZ