Split array using list and array_chunk for dynamic requirements


Split array using list and array_chunk for dynamic requirements



I am using list and array_chunk to split arrays. In my first example I split the array into four pieces using list.



I would like to change the number from 4 to say 8 and have it dynamically do this. Instead of manually creating it in the code. Is this possible ? I assume I could use variable naming as listed in my non working second example below.



How it works now :


list($inv0, $inv1, $inv2, $inv3) = array_chunk($val['inventory'], ceil(count($val['inventory']) / 4));



What I would like is to set something $i = 8 and have it automatically split into 8 chunks dynamically .



Something like :


$i = 8
list(${inv.0}, ${inv.1}, ${inv.2}, ${inv.3},${inv.4},${inv.5},${inv.6},${inv.7}) = array_chunk($val['inventory'], ceil(count($val['inventory']) / $i));



So based on my needs I can split the array into X pieces instead of hard coding it to 4 or 8 etc...





Any time you find yourself creating dynamic variable names you should be using an array instead.
– Barmar
Jun 29 at 18:31




2 Answers
2



You can do a foreach to create the variables you want:


foreach


$array = ['a','b','c','d','e','f','g','h'];
$chunk = array_chunk($array,2);

foreach($chunk as $i => $data) {
${'inv'.$i} = $data;
}

print_r($inv0);
print_r($inv1);

die();



Output


Array ( [0] => a [1] => b )
Array ( [0] => c [1] => d )



There are ways, but I don't think it'd be a maintainable approach since you don't even know how many variables you'd need to process.
However, Felipe Duarte provides a working answer and there are some more over here : php how to generate dynamic list()?



But I'd agree with the top answer.
array_chunk already provides you with pretty much what you are looking for:


array_chunk


$chunks = array_chunk($val['inventory'], ceil(count($val['inventory']) / $i));
print_r($chunks);
// [[0] => ['', ''], [1] => ['','']...]



You can then access it via the indices (such as $chunks[0], $chunks[1]).


$chunks[0]


$chunks[1]





You both have great answers, I overlooked the fact that I don't even need list, I think I am using it because I copied from another piece of my code, thank you for the advice.
– Mike Q
Jun 29 at 18:16






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV