I have a variable that I got out of the database table like this:
while($r = mysql_fetch_array($query) //The query is just: SELECT * FROM stuff_table WHERE userid='$userid'
{
$stuff = $r['stuff'];
}
The stuff variable looks like this: “cars, books, computers, foods” and I made it an array:
//I used:
$array_of_stuff = explode(",", $stuff); //This gave me an array.
Now I wanted to check its values, like this:
if(in_array("cars", $array_of_stuff) && in_array("books", $array_of_stuff))
{
//This line is the problem, I want it to check to see if it has "cars" and "books" in the array but this code is not working for that like it should. Instead of checking and finding both, it just goes on to the next elseif.
echo "Cars and Books";
} elseif(in_array("cars")) {
//
echo "Only cars";
} elseif(in_array("books")) {
echo "Only books";
} else {
echo "Other stuff...";
}
The output I get from this is: “Only cars” instead of “Cars and Books”.
So how can I make my code check the array for 2 or more values before continuing its if/elseif statement? Is it possible with the in_array function?
Var Dump:
array(4) { [0]=> string(4) "cars" [1]=> string(6) " books" [2]=> string(10) " computers" [3]=> string(6) " foods" }
If $array_of_stuff is actually set to
explode(",","cars, books, computers, foods")as you described then the array will have leading spaces before the values other than cars. Thein_array()function doesn’t match substrings of the target elements, so “books” will not match against ” books” in the array.If you need to parse a string like that, you’ll need to make sure you have an exact definition of the format it’s in so you can correctly parse it into an array. If “, ” is the only delimiter and that sequence always represents a delimiter (it’s not ever escaped or quoted, for example), then you could change the
explode(",",...)toexplode(", ",...). If this is data you’re storing, be aware that you shouldn’t invent your own format. Instead, use something likeserialize()(which only PHP understands) orjson_encode()(which is highly portable) to convert native types into a string (and the corresponding decode functions to decode it).Beyond that, storing an array in a field of a row of a SQL table is often, but not always, a sign that the schema is wrong.