I get an Undefined offset: 1 message from this query below. Do not understand why I get it. The echo results in correct data.

echo $url_slug ;
$Exploded_slug = explode($user->ID.'--',$url_slug);
print_r($Exploded_slug );        

$url_slug result: 4--106

print_r($Exploded_slug ) result: Array ( [0] => 4--106 )

$query = "SELECT comments FROM wp_rdp_winners WHERE id = $Exploded_slug[1]";
$comments = $wpdb->get_var($query);

The above query is empty. ID 4 has no comments and does not exist in table. If this means that the ID = 4 has not a comments field, then how can I skip this whit an if statement?

  • Why do you use $Exploded_slug[1] instead of $Exploded_slug[0] in your query? From what I can tell in your code it is empty. Also it is preferred to use lower case for regular variables like yours, so I'd also change $Exploded_slug to $exploded_slug. Oct 21, 2016 at 9:31
  • You're right! Oeps. Blind since today. But you open my eyes. Thanks
    – Hermants
    Oct 21, 2016 at 9:32
  • Alright, gonna put it into a better formatted answer then. Oct 21, 2016 at 9:34
  • ok. then I can give you a positive feedback
    – Hermants
    Oct 21, 2016 at 9:36
  • Now that I've posted my answer and thought more about what you're trying to achieve I got a bit confused xD You sure it works right when you just replace 1 with 0? Because then you'd get WHERE id = '4--106' which is not only the same as WHERE id = $url_slug but also probably wouldn't work the way you want it... Can you provide an example of the url? Oct 21, 2016 at 10:18

1 Answer 1


The problem is that $Exploded_slug[1] is empty, don't forget that arrays are 0-based. So you need to change your query. Also it is preferred to use lower case for regular variables like yours, so I'd also change $Exploded_slug to $exploded_slug.

Here's the code:

$exploded_slug = explode($user->ID.'--', $url_slug);
$query = "SELECT comments FROM wp_rdp_winners WHERE id = $exploded_slug[0]";
$comments = $wpdb->get_var($query);

Actually I don't see the point of making an array here, why not simply concatenate? Using explode here doesn't make much sense anyway, you might want to read this simple explanation of this function with an example. So instead try this:

$exploded_slug = $user->ID . '--' . $url_slug;
$query = "SELECT comments FROM wp_rdp_winners WHERE id = $exploded_slug";
$comments = $wpdb->get_var($query);

But if you're going to add more elements to the $exploded_slug later then use the first variant. But declare the $exploded_slug variable differently, maybe like so:

$exploded_slug = array($user->ID . '--' . $url_slug);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.