Akhil Akhil - 2 months ago 5
PHP Question

Split Array into multiple Array and store in different variables

I want to divide below given array and store it in different variable.For eg.$array1,$array2,$array3.Any help would be grateful.

Array
(
[0] => Array
(
[0] => PVTHR05L006
[1] => PVTHR05L004
[2] => PVTS1K05L004
)

[1] => Array
(
[0] => PVTHR05L004
)

[2] => Array
(
[0] => PVTHR05L006
[1] => PVTHR05L004
[2] => PVTSK05L008
)

)


My expected output is

$array1 = Array
(
[0] => PVTHR05L006
[1] => PVTHR05L004
[2] => PVTS1K05L004
); $array2 = Array
(
[0] => PVTHR05L004
); $array3 = Array
(
[0] => PVTHR05L006
[1] => PVTHR05L004
[2] => PVTSK05L008
);

Answer

As you really don't know the logic- The main logic behind this is variables of variable. Assign two variable called $arr_name and $incre, the $arr_name will be use to create the dynamic array name with the help of $incre.

$mainArr = array(
            array('PVTHR05L006', 'PVTHR05L004', 'PVTS1K05L004'),
            array('PVTHR05L004'),
            array('PVTHR05L006', 'PVTHR05L004', 'PVTSK05L008'),
        );

$arr_name = 'array';
$incre = 1;
foreach($mainArr as $arr){
    ${$arr_name.$incre} = $arr;
    $incre++;
}

print_r($array2);

Online Example, click and see the output. If you need any further help let me know.

Comments