Is it possible to convert an integer into an Array in C or PHP?

Asked

Viewed 183 times

-3

For example:

num = 5634;

array[num];

array[0] = 5;
array[1] = 6;
array[2] = 3;
array[3] = 4;

I explained in a very lay way I believe, but I wanted to know if it is possible for a variable to receive an integer number and take each digit and put in an array.

2 answers

2


In PHP you can do this easily with the function str_split().

Following example:

<?php
    $num = strval(5634);

    $array = str_split($num);

//Retorno: Array ( [0] => 5 [1] => 6 [2] => 3 [3] => 4 )
?>

The function str_split() Converts a string to an array


As explained in the Woss below, when using the function str_split with numbers, it can generate errors, for this, we can work with the function strval() before the number, this will convert to string, avoiding possible errors later.

Follows functional example in phpfiddle

  • 2

    Find it convenient to add to your answer the explanation of why the function works when you pass a number, while she converts one string in array? I mean, why wasn’t I wrong to pass a number?

  • 1

    @Woss the lack of meaning is not in the answer when the question mixes different typing level languages and paradigms.

0

In PHP you can do with the function str_split.

<?php

$num = 5634;

$array = str_split($num);

print_r($array);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.