2

Just a quick newbie PHP syntax question.

I have a variable, let's call it $tabs which always contains a string of numbers separated by commas, like so: 24,35,43,21

I also have a variable that's an array:

$args = array('post_type' => 'page', 'post__in' => array(27,19,29), 'order' => 'ASC');

That's of course WordPress. What I need to do, is place the content of the $tabs variable (numbers) where the numbers inside the array are. I'm rather new to PHP, only understand how to modify some things, but this I can't figure out, no idea how the syntax for it should go.

Anyone able to help? Thanks.

0

2 Answers 2

8
$args['post__in'] = array_merge($args['post__in'], explode(',', $tabs));

Let's explain what I did so you may pick up a thing or two:

  1. explode(',', $tabs) splits a string into pieces at a separator and puts that pieces in an array.
  2. array_merge($arr1, $arr2) will merge the two arrays.
  3. $args['post__in'] will access an array element specified by a key.

Note that array_merge, in this case, will just append the values and you may end up with duplicate numbers. To get rid of duplicates just wrap the merge in array_unique. Like so:

$args['post__in'] = array_unique(array_merge($args['post__in'], explode(',', $tabs)));

And of course, the trivial case when you just want to replace those numbers with brand new ones is

$args['post__in'] = explode(`,`, $tabs);
Sign up to request clarification or add additional context in comments.

2 Comments

+1 if he wants to append. Rather ambiguous if he wants to append or replace. (and explaining)
Fantastic, thanks a lot. First time someone actually explained the solution so I can learn from it. @Jason She ;)
2

$args['post__in'] = explode(",",$tabs);

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.