Forum Moderators: coopster

Message Too Old, No Replies

Finding number in a string of numbers

separated with commas

         

mcibor

9:02 pm on Apr 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a string of numbers separated by comma ',', eg
$str = "1, 3, 56, 8, 9, "; (there's a comma at the end, because it was easier for me to do so)

I need to compare a number ($id) if it's in the string. At first I thought, that strpos() will do the trick, but then it struck me, that 6 will be found (because of 56, ).

So what can I do?

Please help!
Michal Cibor

PS. I thought of exploding the string, but what then?

rojer_31

9:29 pm on Apr 9, 2005 (gmt 0)

10+ Year Member



Okay array_search should do the trick.

$str = array(1, 3, 56, 8, 9, );
$key = array_search('56', $str);
echo $key;// prints '2'

If the value is found within the array, the function returns the corresponding key, else returns false.
note: key index starts from 0.

dreamcatcher

10:48 pm on Apr 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I thought of exploding the string, but what then

Once you explode the string, this creates any array of values. You can then use the in_array function.

$values = explode(",", $str);
$id = 'number';

Then use:

if (in_array($id, $values))
{
//true
}
else
{
//false
}

rojer_31, offers another alternative.

dc

mcibor

12:00 pm on Apr 11, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks guys!

I just needed that in_array function. It's great! (i don't heave to do strpos anymore)

Best wishes
Michal Cibor