4

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.

4
  • 3
    Why don't you do the same thing using loop? Commented Apr 3, 2014 at 11:52
  • Use 2D arrays and loops. Commented Apr 3, 2014 at 11:53
  • Write it into text file... Use php to split it in way you want it to... Commented Apr 3, 2014 at 11:53
  • @Dikesh Can you point me in the direction of how I would do that please Commented Apr 3, 2014 at 11:56

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Simplest solution. but you could also change the loop to cover arrays with values A-MTP-2- and A-MTP-3-

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.