Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying an array in PHP

I have the following Arrays which I need to define in PHP which I've done in a very basic way:

$ch1 = array("A-MTP-1-1","A-MTP-1-2","A-MTP-1-3","A-MTP-1-4"); 
$ch2 = array("A-MTP-1-5","A-MTP-1-6","A-MTP-1-7","A-MTP-1-8"); 
$ch3 = array("A-MTP-1-9","A-MTP-1-10","A-MTP-1-11","A-MTP-1-12");

$ch4 = array("A-MTP-2-1","A-MTP-2-2","A-MTP-2-3","A-MTP-2-4"); 
$ch5 = array("A-MTP-2-5","A-MTP-2-6","A-MTP-2-7","A-MTP-2-8"); 
$ch6 = array("A-MTP-2-9","A-MTP-2-10","A-MTP-2-11","A-MTP-2-12");

$ch7 = array("A-MTP-3-1","A-MTP-3-2","A-MTP-3-3","A-MTP-3-4"); 
$ch8 = array("A-MTP-3-5","A-MTP-3-6","A-MTP-3-7","A-MTP-3-8"); 
$ch9 = array("A-MTP-3-9","A-MTP-3-10","A-MTP-3-11","A-MTP-3-12");

But I was thinking there must be a simple way of writing this rather than writing out each one but not sure where to start, Would someone be able to point me in the right direction to simplifying this PHP as I will also be repeating it for the above but with B instead of A for each one.

like image 795
Vince P Avatar asked Dec 25 '22 11:12

Vince P


1 Answers

Use range() , array_chunk and extract to get this done

<?php

for ($i = 1; $i <= 3; $i++) {           # Pass 3 as you need three sets
    foreach (range(1, 12) as $val) {    # 1,12 again as per your requirements
        $arr[] = "A-MTP-$i-" . $val;

    }
}
foreach (array_chunk($arr, 4) as $k => $arr1) {    # Loop the array chunks and set a key
    $finarray["ch" . ($k + 1)] = $arr1;
}
extract($finarray);   # Use the extract on that array so you can access each array separately
print_r($ch9);        # For printing the $ch9 as you requested.

Demo

OUTPUT : (Illustration for $ch9 part alone)

Array
(
    [0] => A-MTP-3-9
    [1] => A-MTP-3-10
    [2] => A-MTP-3-11
    [3] => A-MTP-3-12
)

After doing that , you can use array_chunk to split the array to length of 4.

like image 100
Shankar Narayana Damodaran Avatar answered Dec 28 '22 05:12

Shankar Narayana Damodaran