cronos
cronos

Reputation: 568

How to implode an array and display the values with "x" amount of digits?

I want to display each value of the array with 4 digits; if the value has less than 4 digits it has to be padded with leading zeros.

<?php 
$x = array(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024);
echo implode(", ",$x) . "<br>";
echo sprintf("%04s", implode(", ",$x)) . "<br>";
?>

If I run that code; it will output:

1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024
1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024

all I want is to figure out how to output this:

0001, 0002, 0004, 0008, 0016, 0032, 0064, 0128, 0256, 0512, 1024

Upvotes: 0

Views: 344

Answers (2)

felipsmartins
felipsmartins

Reputation: 13549

As you want format each array element, array_map() is probally the best option to go as it applies a callback for each elements of the given array.

$x = array(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024);

$formatted = array_map(function ($n) { return sprintf("%04s", $n); }, $x);

print_r($formatted);

Upvotes: 3

axiac
axiac

Reputation: 72266

You say:

I want to display each value of the array with 4 digits; if the value has less than 4 digits it has to be padded with leading zeros.

Let's translate your question into code:

$x = array(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024);
echo(
    implode(', ',
        array_map(                     // each value of... -----------------+
            function ($value) {        //                                   |
                return str_pad(                     // padded               |
                    $value, 4, '0', STR_PAD_LEFT    // with leading zeros   |
                );                                  //                      |
            },                         //                                   |
            $x                         // <----------- ... the array -------+
        )
    )
);

sprintf() can also be used (as you have tried). However, if the values from your array are numbers it's probably better to use the %d format specifier:

function ($value) {
    return sprintf('%04d', $value);
}

Upvotes: 2

Related Questions