1

I need to break an integer where each digit in this integer is to be an element in an array like this:

$x = 123;
var_dump($x_array);

Will out put something like this:

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

Thanks.

2 Answers 2

3
print_r(str_split($x));

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

Don't forget the "php" tag next time!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to Graphox I got this solution: $x= 1234; $array = array(); $x = str_split($x); foreach($x as $number){ $number = intval($number); array_push($array,$number); } var_dump($x); var_dump($array); but after some work and the help of Ayyash I got this: $x = 1234; $y = 1; $array = array(); while($y){ $remainder = $x % 10 ; array_push($array, $remainder); $x = $x - $remainder; $x = $x /10; if($x == 0){ $y = 0; } }
1

(1) Array of digits as strings:

$x_array = str_split($x);
var_dump($x_array);

    0 => string '1' (length=1)
    1 => string '2' (length=1)
    2 => string '3' (length=1)

(2) Array of digits as integers:

$x_array = array_map('intval', str_split($x));
var_dump($x_array);

    0 => int 1
    1 => int 2
    2 => int 3

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.