Jump to content

Archived

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

webwired

Splitting a 4 number variable into 4 different variables

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?

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
You can even do $i++ instead of the $i = $i + 1. Not important, just a little side not for your own personal knowledge. kenrbnsn's example is excellent, overlooking the - 1.

Share this post


Link to post
Share on other sites
After the four digit number is broken down into four separate numbers, can you then turn it into a letter as A=0, B=1 and so on? I thought this was supposed to work, but it didn't...
[code]
$digit1 = ($seg1digit1(Ord('A')));
[/code]

Share this post


Link to post
Share on other sites

×

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.