0

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?

0

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Since some web hosting providers disable sprintf for security reasons I will choose your answer. Thank You!
Is str_split necessary? You can treat strings as an array of characters anyway.
1
<?php
$users=349;
$values=str_split(sprintf('%05d', $users));
print_r($values);
?>

Demo

Comments

1

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!

Comments

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.