PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] Why Doesn't Variable Work When I Assign It In Array?

 May 16, 2022     arrays, php, wordpress     No comments   

Issue

I need to use a variable in the below code but it doesn't work, I don't understand why.

Working code;

$the_query = new WP_Query( array(
    'post__in' => array(
        16405,16362,16290,16434,16661
    ),
) );

Code that doesn't work;

$featured_content_id = get_theme_mod( 'laura_featured_content_id' );
$the_query = new WP_Query( array(
'post__in' => array(
$featured_content_id
),
) );

When I look at $featured_content_id variable using echo and var_dump(), it seems to be correct. Which means the result is 16405, 16362, 16290, 16434, 16661 but it doesn't work inside a array. Also it doesn't work if I directly use $featured_content_id = '16405, 16362, 16290, 16434, 16661'. Do I have to write it inside array?


Solution

Assuming $featured_content_id is a string:

You probably want explode(',', $featured_content_id) and not array($featured_content_id). And in case it has to be a number and not a string, you'd also need array_map('intval', ...) around it.

This is because what you currently do will give you an array like array('16405,16362,16290,16434,16661') which is an array with one element that is a string. What you actually want is to split the string (using , as separator) into an array with one element for each part.

$the_query = new WP_Query( array(
    'post__in' => array_map('intval', explode(',', $featured_content_id)),
) );

Assuming $featured_content_id is an array:

If it's already an array, all you need is to pass the variable directly, without wrapping it in array( ).

$the_query = new WP_Query( array(
    'post__in' => $featured_content_id,
) );


Answered By - CherryDT
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing