BTB BTB - 1 month ago 9
PHP Question

String is different when written and saved in variable

Okay, so I have this confusing problem with a string. I'm using a loop to construct the string, and I use

print_r($exclude)
to see the result. The output of the string is:

101,102,135

... which is correct. Then I'm trying to use
$exclude
in an argument-array for a WordPress-query:

'terms' => array($exclude),


In short this should exclude posts from the categories with ID's mentioned above. But this does not work as intended. Unless if I write the numbers directly like this, it works:

'terms' => array(101,102,135),


So what is the difference between the
$exclude
-string and writing the numbers manually...!?

Answer

When you do this

'terms' => array($exclude)

Your terms array looks like this:

Array
(
    [0] => 101,102,135
)

Solution

'terms' => explode(',', $exclude)

$exclude becomes

Array
(
    [0] => 101
    [1] => 102
    [2] => 135
)

You are assigning a string to the 0-th key in array, whereas you should be passing array elements.

explode will split up your string into an array based on a passed delimiter (in your case a comma).

Comments