0

I want to Search in Array value by in_array Function and For loop. My code:

$input = "a";
$arrays = array("cdf","abs","tgf");

$counter = count($arrays);

for ($i=0; $i<$counter; $i++){

    if(in_array($input,$arrays) !== true){
        echo "Found <br>";
    } else {
        echo "Not Found";
    }

}

Output:

Not Found
Found
Not Found

But, if(in_array($input,$arrays[$i]) !== true) not working.

1 Answer 1

2

The reason in_array("a", "cdf"), which is what in_array($input, $arrays[$i]) could become, isn't working is because "cdf" isn't an array.

Are you trying to find array elements in $arrays that contain the letter a?
In that case you should search array elements with strpos() to determine if a string contains another string. You can also use foreach instead of for if iterating over the array is all you want to do.

$input = "a";
$arrays = array("cdf","abs","tgf");

foreach ($arrays as $key => $value)
{
    if (strpos($value, $input) !== false)
        echo "Found in $key<br>";
    else
        echo "Not Found<br>";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, You say "cdf" isn't an array. You mean in_array only worked for all array() value and can't use for specific value ?
Read the manual for in_array(), it checks if a specific element is in an array, not part of a string which is in an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.