1

I have a array like that :

 $myarray=  'zzz,aaa,bbb'  ; 

and want use it in mysql IN clause like that :

 "...  WHERE ids IN ($myarray) "   // didnt work 
 "...  WHERE ids IN ('$myarray') " // didnt work

the error im getting is that the first value in that array zzz says that zzz is not a column name . so i understand that i must separate the values with quotes to be like that :

 $myarray=  ' "zzz","aaa","bbb" '  ;

But i have no clue to do that . any help would be much appreciated.

5
  • Because it really isn't an array, it's a string. You need to implode with the appropriate quotes and commas. Commented Mar 2, 2015 at 19:31
  • The end result should look like this: WHERE ids IN ('zzz','aaa','bbb') Commented Mar 2, 2015 at 19:33
  • @JayBlanchard you mean i use this ` ids IN implode(", ", $myarray); ` ? Commented Mar 2, 2015 at 19:34
  • Lot's of good answers here @ScooterDaraf - the one liners are especially elegant. My example shows what is going on line by line. Commented Mar 2, 2015 at 19:36
  • 1
    As a side note, you should maybe not call your variable $myarray if it isnt an array. Giving good names, makes it easier to maintain code. Commented Mar 2, 2015 at 19:44

3 Answers 3

4
$myarray = 'zzz,aaa,bbb';
$myarray = implode("','",explode(',',$myarray));
$query   = "..... WHERE ids IN ('$myarray')";
Sign up to request clarification or add additional context in comments.

1 Comment

I dont know why id doesnt work with 2 strings and more, it works just with single string .
3

You need to explode() your string and then implode() it -

$myarray = 'zzz,aaa,bbb'; 
$realArray = explode(',', $myarray);
$stringForIn = "'" . implode("','", $realArray) . "'";
echo "WHERE ids IN ($stringForIn)";

4 Comments

I dont know why id doesnt work with 2 strings and more, it works just with single string
Without knowing more about your database it would be hard to know why it isn't working. Can you update your original post with the entire query and your table layout @ScooterDaraf?
Can you echo the full query @ScooterDaraf? So far I'm not seeing an issue.
Let us know if you need us to look further @ScooterDaraf. Make sure to update your post with the appropriate code so we can see what is going on.
1

Try that :

$myarray=  'zzz,aaa,bbb'  ; 
echo implode '"' . ('","', explode(',', $myarray)) . '"';

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.