1

I'm trying to add 0 every time when number is grater or equal to 2 length. For example: I don't want a1,a10, I want a01,a10.

$a_l_demographics = [11,3,13];
$a_p_demographics  = ['a','b','c'];
$a_r_demographics = [];
$c_demographics_values = array();
$a_c_demographics = min(count($a_l_demographics), count($a_p_demographics));

for ($i = 0; $i < $a_c_demographics; $i++) {

  for ($j = 1; $j <= $a_l_demographics[$i]; $j++) {

    $a_r_demographics[] = $a_p_demographics[$i] . $j;

    // I tried to do something like this, but doesn't work.
    if (strlen(implode($a_r_demographics)) >= 2) {
      $a_r_demographics[] = '0'.$a_p_demographics[$i] . $j;
    } else {
      $a_r_demographics[] = $a_p_demographics[$i] . $j;
    }

    // or even this
    /*
    switch (true) {
      case $i <= 10:
        $a_r_demographics[] = '0'.$a_p_demographics[$i] . $j;
        break;
    }
    */

    echo implode($a_r_demographics);

  }

}

Result should be:

a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,b01,b02,b03,c01,c02,c03,c04,c05,c06,c07,c08,c09,c10,c11,c12,c13

  • Possible duplicate of [Formatting a number with leading zeros in PHP](https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php) – Spoody Jul 30 '18 at 18:12
  • `add 0 when number is greater or equal to 2 length`? So you want to add 0 to, say, 100? – Deltharis Jul 30 '18 at 18:25
  • 1
    You should try something like str_pad() http://php.net/str_pad – ash__939 Jul 30 '18 at 18:25

1 Answers1

2
<?php
    $a_l_demographics = [11,3,13];
    $a_p_demographics  = ['a','b','c'];
    $a_r_demographics = [];
    $c_demographics_values = array();
    $a_c_demographics = min(count($a_l_demographics), count($a_p_demographics));

    for ($i = 0; $i < $a_c_demographics; $i++) {
        for ($j = 1; $j <= $a_l_demographics[$i]; $j++) {
            $a_r_demographics[] = $a_p_demographics[$i] . str_pad($j, 2, 0, STR_PAD_LEFT);
        }
    }
    echo implode($a_r_demographics, ',');
ash__939
  • 1,614
  • 2
  • 12
  • 21