简体   繁体   中英

How to split string from commas(,) and store into separate variables in PHP

I want to know how can I split a string and store that into separate variables. Suppose I have a string "healthy,foody,fitness,food" and now I want to store each value in separate variable. I already converted them into array with explode()

Now how can i store each value in separate variable like say

$health = "healthy";
$foody = "foody";
$fitness = "fitness"; 

and so on.

The main purpose of doing this is, I am trying to make an E commerce website with core PHP and I have a value called "tags" in database where i store tags in comma separated values and I have to use those tags for sorting "Similar Products" and that's why I need them in separate variable so that I can

"SELECT * FROM products WHERE tags='$health' OR tags='$foody'";

You get my point right? All helps appreciated! Have a great day!

If you want to find by tags from string, you can do that:

$string = "healthy,foody,fitness,food";
$tags = explode(",", $string);
$tags = array_map(function($v) {return "'".trim($v)."'"; }, $tags);
$sql = "SELECT * FROM products WHERE tags IN(".implode(",", $tags).")";

output is:

SELECT * FROM products WHERE tags IN('healthy','foody','fitness','food')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM