David Biga
David Biga

Reputation: 2801

Retrieving a number at a time from a string - PHP

I am working on a project of mine and came across an interesting problem. Lets say you have a string that contains 5,5689, 1546,572 and with this string, lets say I want to separate each of the numbers separated by a comma and store them into a database individually.

For instance, it would take 5 and store that into the database. Than it would take 5689 and store that into the database.

How would you ladies and gentlemen go about this?

David

Upvotes: 0

Views: 56

Answers (2)

Emilio Gort
Emilio Gort

Reputation: 3470

You can use explode()

From manual: Returns an array of strings created by splitting the string parameter on boundaries formed by the delimite

Example:

$number = '5,5689,1546,572';
$numberArray = explode(',',$number);
echo numberArray[0];//Output: 5
echo numberArray[1];//Output: 5689 
echo numberArray[2];//Output: 1546 
echo numberArray[3];//Output: 572

Or use foreach to loop over the new array

 foreach($numberArray as $key => $value){
    echo $value.'<br>';
 }

Output:

5

5689

1546

572

Upvotes: 1

Cleiton Souza
Cleiton Souza

Reputation: 881

I believe that you do not have problems to save the information in the bank .. but about breaking comma, u can use the explode function

explode(',', $string);

and now you have this array:

0 => 5
1 => 5689
2 => 1546
3 => 572

Upvotes: 3

Related Questions