i have the following array:
$list = array('item1','item2','item3','item4','item5','item6');
i need to take this array and break it into smaller arrays within 1 array for a program. Each small array needs to have '999999' at index 0, followed by the next 2 items in the $list
array, then followed by the same 2 items in the $list
array, but with .pdf
at the end, to create a filename. So the final result would be like this:
$newList = array( array(999999, "item1" , "item2", "item1.pdf", "item2.pdf"),
array(999999, "item3" , "item4", "item3.pdf", "item4.pdf"),
array(999999, "item5" , "item6", "item5.pdf", "item6.pdf")
);
the original list array may contain up to 100 values at sometimes. What is the best way to achieve this?
You can use array_splice
to remove 2 elements at each iteration and build your results array. Something like that:
$list = array('item1','item2','item3','item4','item5','item6');
$result = array();
while (!empty($list)) {
$array = array_splice($list, 0, 2);
if (count($array) == 2) {
$result[] = array(999999, $array[0], $array[1], $array[0] . ".pdf", $array[1] . ".pdf");
} else {
$result[] = array(999999, $array[0], '', $array[0] . ".pdf", '');
}
}
var_dump($result);
As a start, take a look at array_chunk()
.
You could add the static elements (999999
, *.pdf
) to the result with some custom code. But at that point a solution such as the one provided by Mathieu Imbert is a better option.
Note: PHP has over a hundred array functions. Learning these will make you a better PHP developer.
You can also use each
and a normal while loop:
// solution without an array_* function
$newList = array();
while((list(,$a) = each($list)) && (list(,$b) = each($list))) {
$newList[] = array(999999, $a, $b, "$a.pdf", "$b.pdf");
}
print_r($newList);
or no loop at all (requires PHP >= 5.3):
$newList = array_map(function($e) {
return array(999999, $e[0], $e[1], "{$e[0]}.pdf", "{$e[1]}.pdf");
}, array_chunk($list, 2));
print_r($newList);