1

I have the following PHP code which creates Arrays of A-MTP-1-1, A-MTP-1-2, etc....

<?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.
?>

I need the arrays to have a 0 infront of the single digit numbers so it would become A-MTP-01-01, A-MTP-01-02, etc... but not have a zero when it gets to the double digit numbers.

How can I achieve what I need as I have tried the following and it's made no change:

for ($i = 01; $i <= 12; $i++) {           # Pass 3 as you need three sets
    foreach (range(01, 12) as $val) {    # 1,12 again as per your requirements
        $arr[] = "A-MTP-$i-" . $val;
Vince P
  • 1,781
  • 7
  • 29
  • 67
  • possible duplicate of [Zero-pad digits in string](http://stackoverflow.com/questions/324358/zero-pad-digits-in-string) – FuzzyTree May 28 '14 at 16:13

2 Answers2

4

PHP's sprintf is your friend.

So this line
$arr[] = "A-MTP-$i-" . $val;

would change to this
$arr[] = sprintf("A-MTP-%02d-%02d", $i, $val);

Florian Grell
  • 995
  • 7
  • 18
2

I'd say you should use sprintf as follows:

$arr[] = sprintf("A-MTP-%02d-%02d", $i, $val);
Uxonith
  • 1,602
  • 1
  • 13
  • 16