Jump to content
• Sign Up

#### Archived

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

# Splitting up 4 numbers

## Recommended Posts

In a form I have, a user inputs a 4 numerical value into a text box.

how would I go about splitting this into 4 variables?

[u]eg[/u]

[b]9172 [/b] entered

var1 = [b]9[/b]
var2 = [b]1[/b]
var3 = [b]7[/b]
var4 = [b]2[/b]

Can this be done - and if so, how?

Thanks in advance...

#### Share this post

##### Share on other sites
Use substr(). http://www.php.net/manual/en/function.substr.php

#### Share this post

##### Share on other sites
.. and on the page Ober cites, the example #1 code shows exactly how you could do what you ask.

#### Share this post

##### Share on other sites
Yeah... you could use the curly brace method as well.

#### Share this post

##### Share on other sites
...or, you could just treat the string as an array:
[code]
<?php
\$string = "Test String";
for (\$i = 0; \$i < strlen(\$string); \$i++) echo "{\$string[\$i]}<br />\n";
?>
[/code]

so, for your example, i'd do something like this:
[code]
<?php
\$string = "9172";
for (\$i = 1; \$i <= strlen(\$string); \$i++) {
eval("\\$var\$i = \\$string[\\$i - 1];");
}
?>
[/code]

good luck

#### Share this post

##### Share on other sites
Sorry, I've tried to follow those examples but i still cant seem to split up the the variable \$value into the four I need.

Any chance of putting an example on here using \$value as the 4 digit value of 2468?

Sorry to ask - still trying to learn

#### Share this post

##### Share on other sites
try my edited post above... that produces \$var1, \$var2, etc... containing the 4 digits

#### Share this post

##### Share on other sites
It works! Thank you so much to everyone who helped!!!!!!

#### Share this post

##### Share on other sites
one other note... some people on here would frown upon using eval() for something like this, so you could also do it like this:
[code]
<?php
\$string = "9172";
for (\$i = 1; \$i <= strlen(\$string); \$i++) {
\${"var\$i"} = \$string[\$i - 1];
}
?>
[/code]

×

• Chat

## 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.