Question:
PHP get numbers from string?
wata_tempora
2008-11-18 18:31:14 UTC
I'm trying to get an input from an html text field of "1,2,3,4,5"

and I need to make a function for getting the numbers in the String separated by a comma and put it in an array. I tried using Split(",",$String) but cannot access the array, can anyone help? Thanks

for example
$str = "1,2,3,4,5";

$array = getnumber($str);

echo $array[0];
echo $array[3];
etc...
Three answers:
Chris C
2008-11-18 18:56:24 UTC
Try doing this:

$array = explode(",", $str);

foreach ($val in $array)

echo $intval($val);



Obviously you don't have to convert the value in the array value by calling "intval()", that just merely converts it to an integer.
2008-11-19 02:56:35 UTC
use an explode function if you want to get the numbers separated by ","

like this code:

$str = "1,2,3,4,5";

$exp = explode(',',$str);

echo $exp[0]; // the result would be 1;

echo $exp[1]; // the result would be 2;

etc....

because the exploded string will return an array....



I just would like to offer you this...

Earn extra money online, sign up here: http://www.getafreelancer.com/affiliates/lxculango/
EFG
2008-11-19 02:40:47 UTC
You're using the wrong function, you want to EXPLODE.



If $str = "1,2,3,4,5"



If you

$exploded = explode(",", $str);



Then you'd get



$exploded[1] = 1

2 = 2

etc.



http://us2.php.net/explode


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...