Asim Zaidi
Asim Zaidi

Reputation: 28344

check in a string php

I have a string and it can contain values like this $string = '1,2,3,4,5'; I wanna put a check that will see if the string contains 4 or 5 if it contains 4 or 5 then I want to echo success otherwise if it contains 9 or 10 I wanna echo fail

I know there is a n in_array function but not sure how to use it thanks

Upvotes: 0

Views: 153

Answers (6)

ivan73
ivan73

Reputation: 705

Check all at once :)

if(in_array(array(4,5), explode(',', $string))) echo "success";

if(in_array(array(9,10), explode(',', $string))) echo "failure";

Upvotes: 1

bimbom22
bimbom22

Reputation: 4510

you can use strpos() to check for the existence of a substring inside a string, like this:

if(strpos(','.$string.',', ','.$number_to_check_for.',') !== false) {
    //success, substring was found
} else {
    //error, substring was not found.
}

or you could explode it into an array then use in_array():

$array = explode(',',$string);

if(in_array($number_to_check_for, $array)) {
    //success substring found
} else {
    //error, substring not found
}

But I would recommend the first solution, as it is cleaner and more efficient.

Upvotes: 1

Sergey Eremin
Sergey Eremin

Reputation: 11076

$goodString = '1,2,3,4,5';
$badString = '1,2,3,7,8,9,10';

function checkString($str) {
    $arr = explode(',', $str);
    $message = 'no message';
    if (
        in_array(4, $arr)||
        in_array(5, $arr)
    ) {
        $message = 'success';
    } else if (
        in_array(9, $arr)||
        in_array(10, $arr)
    ) {
        $message = 'fail';
    }
    echo $message;
}

checkString($goodString); // prints success
checkString($badString); // prints fail

Upvotes: 1

GOsha
GOsha

Reputation: 689

$set = array (1,2,3...,n); //you can use range() function if the numbers going one by one or explode if you have a string
if(in_array($var,$set))
{
   Echo 'IS in ARRAY!';
} else {
   Echo 'fail';
}

Upvotes: 1

Scott Saunders
Scott Saunders

Reputation: 30414

You can test for the number 4 like this:

if(in_array('4', explode(',', $string))) echo "it's in there";

or just by string searching:

if(strpos(',4,', ','.$string.',') !== false) echo "it's in there";

Upvotes: 4

hollsk
hollsk

Reputation: 3137

in_array won't help you here because you have a string, not an array. What you're looking for is the strpos() function:

http://php.net/manual/en/function.strpos.php

Note that if it doesn't find what it's looking for in your string, it'll return false on its own, so all you have to do is check whether it returns a result or not to meet your conditions.

Upvotes: 1

Related Questions