PHP array simplification

I have the following arrays that I need to define in PHP, which I did in a very simple 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 thought there should be an easy way to write this, not write, but not sure where to start. Can someone point me in the right direction to simplify this PHP, as I will also repeat it for the above, but with B instead of A for each.

+4
source share
1 answer

Use range(), array_chunkand extractto accomplish this.

<?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 :(only for part $ch9)

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

After that, you can use array_chunkto divide the array by length 4.

+10
source

Source: https://habr.com/ru/post/1534815/


All Articles