Kristjan Kirpu
Kristjan Kirpu

Reputation: 682

Separating numbers to different strings or an array

I'm using Laravel 4 to count my database entries and I need to split each number to a different string or an array.

$users = DB::table('users')->count();

The result is for example 349, and I need to get:

$string1 = 0;
$string2 = 0;
$string3 = 3;
$string4 = 4;
$string5 = 9;

or an array

$string[0] = 0;
$string[1] = 0;
$string[2] = 3;
....

I specifically need 5 numbers, even if the count(); result is 349 I need to add 0 and 0 before it, or if I get 1234 - one zero needs to be before it because I need 5 numbers.

What do I need to use to get wanted results?

Upvotes: 0

Views: 49

Answers (3)

Amal Murali
Amal Murali

Reputation: 76666

As commented very early:

You can use sprintf:

$num = 349;
$string = str_split(sprintf('%05d', $num));
print_r($string);

Output:

Array
(
    [0] => 0
    [1] => 0
    [2] => 3
    [3] => 4
    [4] => 9
)

Live demo!

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

<?php
$users=349;
$values=str_split(sprintf('%05d', $users));
print_r($values);
?>

Demo

Upvotes: 1

Bora
Bora

Reputation: 10717

Using with str_split and str_pad

$users = DB::table('users')->count();

$array = str_split(str_pad($users, 5 , 0, STR_PAD_LEFT));

Output of Array

array (size=5)
  0 => string '0' (length=1)
  1 => string '0' (length=1)
  2 => string '3' (length=1)
  3 => string '4' (length=1)
  4 => string '9' (length=1)

Upvotes: 2

Related Questions