How to find a certain value in array delimited by white space -- In_Array or array_key_exists

I have a MySQL column value stored as an array delimited by white space like this:

one two three four five six

$array holds the values as noted above (one two three four five six).
$number = ‘two’;

I want to determine if, say, “two” exists in the array, but I can’t get my syntax correct.


$matchSearch = "$array";

if (in_array ( "$number", $matchSearch))

{
echo "It's there";
}

else
{
echo "Nope. Not there.";
}

Thanks.

The array values need to be quoted (unless integer) and separated by a comma.

$array = array('one','two','three','four','five','six');

P.S. And don’t quote variables.

Hmm. Not a very versatile solution. I need to quote the variable.

Okay lets give a couple of points.

1: Dont store arrays as strings.
2. Your ‘array’ is a string (there is no such thing as “an array delimited by”). Treat it as such.
3. There is no value in quoting a variable alone when it is already a string. $matchSearch = “$array”; and $matchSearch = $array; are equivalent statements in this case.
4. If $array actually IS an array, $matchSearch = “$array” would make $matchSearch contain the word “Array”.

1 Like

Yes if “$array” is a string, you could explode it to get an array to then search with.

<?php
$number = "two";
$array = "one two three four five six";
$matchSearch = explode(' ',$array);
if (in_array ($number, $matchSearch))
{
echo "It's there";
}
else
{
echo "Nope. Not there.";
}
?>

If “$array” is truly an array then you will need the array KEY as shown in this example.

<?php
$number = "two";
$array = array("one two three four five six");
$matchSearch = explode(' ',$array[0]);
if (in_array ($number, $matchSearch))
{
echo "It's there";
}
else
{
echo "Nope. Not there.";
}
?>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.