Matthias O.
Matthias O.

Reputation: 312

Put number separately in array

I would like to put a number separately in an array

ex.

$num = 345;

should be in an array so i can call the numbers as

$num[1] (which should return 4)

I tried str_split($num,1) but without succes.

Thanks

EDIT -------

After some more research str_split($num,1) actually did the trick. (thanks, Crayon Violent)

Upvotes: 0

Views: 59

Answers (3)

kraysak
kraysak

Reputation: 1756

$num = 345;

$arr1 = str_split($num); print_r($arr1); //Array ( [0] => 3 1 => 4 [2] => 5 )

echo $arr11; //4

str-split

Upvotes: 1

75inchpianist
75inchpianist

Reputation: 4102

while ($num >0) {
  $arr[i] = $num %10;
  $num = $num/10;
  i++
}
//this leaves the array in reverse order i.e. 543
//to flip 
array_reverse($arr);

Upvotes: 0

Andy Lester
Andy Lester

Reputation: 93676

If you are just trying to get individual characters from the string, use substr.

$second_digit = substr( $num, 1, 1 );

Upvotes: 1

Related Questions