Use variable as an array argument

Discussion in 'PHP' started by levani, Aug 4, 2009.

  1. #1
    The value of the variable $numbers is 1, 2, 3, 4, 5 but this code doesn't work:

    $wp_query->query(array('post__in'=>array($numbers),'showposts'=>5,'paged'=>$paged));
    PHP:
    When I type those numbers manually it works:

    $wp_query->query(array('post__in'=>array(1, 2, 3, 4, 5),'showposts'=>5,'paged'=>$paged));
    PHP:
    What is the problem?
     
    levani, Aug 4, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    so $numbers is a string containing the text "1, 2, 3, 4, 5"?

    If so, what you're doing is creating an array with a string in it, not what you wanted.

    To accomplish that, simply do explode(', ', $numbers) instead:

    
    $wp_query->query(array('post__in'=> explode(', ', $numbers),'showposts'=>5,'paged'=>$paged));
    PHP:
     
    premiumscripts, Aug 4, 2009 IP
  3. levani

    levani Peon

    Messages:
    61
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This code doesn't seem to work...

    Here is how I get the $numbers string:

    <?php
    $post_ids = $wpdb->get_col("SELECT comment_post_ID FROM $wpdb->comments WHERE user_id = $current_user->ID AND comment_approved = '1' ");
    $numbers = implode(', ', $post_ids);
    ?>
    PHP:
    The first line gets IDs from database and the second line adds , symbol in order to use these numbers as an array argument. Is anything wrong?
     
    levani, Aug 4, 2009 IP
  4. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You don't need to do the implode, remove that line and just do:

    $wp_query->query(array('post__in'=> $post_ids,'showposts'=>5,'paged'=>$paged));
    PHP:
    And if that doesn't work do:

    echo "<pre>"; print_r($post_ids); echo "</pre>";
    PHP:
    and show us the output as I'm not sure how wordpress returns the db results.
     
    premiumscripts, Aug 4, 2009 IP
  5. Sky AK47

    Sky AK47 Member

    Messages:
    298
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    45
    #5
    Sky AK47, Aug 4, 2009 IP
  6. levani

    levani Peon

    Messages:
    61
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    It works. Thank you very much!!!
     
    levani, Aug 4, 2009 IP