0

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!

4
  • 2
    where i store tags in comma separated values... The problems start here! never store values comma separated into db... think about normalization Commented Jul 13, 2018 at 10:35
  • @B001ᛦ, then how can i implement features like tags and cart? Commented Jul 13, 2018 at 10:46
  • then how can i implement features like tags and cart?... I think I already gave you the hint... normalization! Commented Jul 13, 2018 at 10:47
  • if you have already an array .. why you need the vars name ??? use the array by index Commented Jul 13, 2018 at 10:50

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

Comments

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.