Jump to content

Splitting a 4 number variable into 4 different variables


webwired

Recommended Posts

Hi, I've tried several splitting techniques on php.net, but I can't seem to find one that will allow me to do something like this...

Split this 4 number variable into 4 different variables, in order.
$number = '3956';

Such as this.

$digit1 = '3';
$digit2 = '9';
$digit3 = '5';
$digit4 = '6';

Could anyone please help me?
Need to use substr()

Example:

[code]
<?php
$number = "2345";
echo $number . "<br>";

$digit1 = substr($number,0,1);
$digit2 = substr($number,1,1);
$digit3 = substr($number,2,1);
$digit4 = substr($number,3,1);

echo $digit1 . "<br>";
echo $digit2 . "<br>";
echo $digit3 . "<br>";
echo $digit4 . "<br>";
?>
[/code]
Actually, in PHP5 there is a function that does thism [a href=\"http://www.php.net/str_split\" target=\"_blank\"]str_split[/a](). If you are still using PHP4, you can treat the string like sort of an array:
[code]<?php
$str = '2345';
for ($i=0;$i<strlen($str);$i++) {
   $x = $i - 1;
   $var = 'digit' . $x;
   $$var = $str{$i};
}
?>[/code]

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.