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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.