Jump to content


Photo

Splitting a 4 number variable into 4 different variables


  • Please log in to reply
7 replies to this topic

#1 webwired

webwired
  • Members
  • PipPip
  • Member
  • 16 posts

Posted 12 March 2006 - 01:02 AM

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?


#2 sgb162

sgb162
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 12 March 2006 - 01:17 AM

Need to use substr()

Example:

<?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>";
?>


#3 webwired

webwired
  • Members
  • PipPip
  • Member
  • 16 posts

Posted 12 March 2006 - 01:35 AM

Thank you, works like a charm.

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 12 March 2006 - 02:38 AM

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:
<?php
$str = '2345';
for ($i=0;$i<strlen($str);$i++) {
   $x = $i - 1;
   $var = 'digit' . $x;
   $$var = $str{$i};
}
?>

Ken

#5 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 12 March 2006 - 09:30 PM

$x = $i + 1;

would be an improvement ;-)
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#6 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 12 March 2006 - 11:22 PM

oops! :-)

#7 txmedic03

txmedic03
  • Members
  • PipPipPip
  • Advanced Member
  • 313 posts
  • LocationCall, TX, USA

Posted 13 March 2006 - 09:24 AM

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.

SEMPER FIDELIS!

I can't stop you from doing something silly, but at least I can help you do it right.


#8 webwired

webwired
  • Members
  • PipPip
  • Member
  • 16 posts

Posted 13 March 2006 - 08:24 PM

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...
$digit1 = ($seg1digit1(Ord('A')));





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users