简体   繁体   中英

How do I break an array into smaller arrays PHP

This is what I want to do. I have an array that I then want to split up into all the elements that it has. For example I have:

$originalArray = array(1,2,3,4,5);

And I want to split this array to look like this.

$array1 = array(1);
$array2 = array(2);
$array3 = array(3);
$array4 = array(4);
$array5 = array(5);

if the original array had more elements then I would like it to split into all those arrays.

for($i = 0; $i < count($originalArray); $i++ ){

    /*this is where I am stuck, I would like it if the word "array" would be able to concat with the iterator $i to make $array1, $array2 and so on*/ 

    $array.$i = array($originalArray[$i]);


}

try this :

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');

echo "<pre>";
print_r(array_chunk($input_array, 1));
?>

Ref : http://php.net/manual/en/function.array-chunk.php

<?php
$originalArray = array(1,2,3,4,5);
$temp = array();
$i=1;
foreach ($originalArray as $elem) {
  $temp['array' . $i] = $elem;
  $i++;
}
extract($temp);
print_r($array1);echo '<br/>';
print_r($array2);echo '<br/>';
print_r($array3);echo '<br/>';
print_r($array4);echo '<br/>';
print_r($array5);echo '<br/>';

Demo

try this

$originalArray = array(1,2,3,4,5);

$splitArray = explode(",",$orginalArray);

for($i = 0; $i < count($originalArray); $i++ ){


    $array.$i = array($splitArray($i));


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM