If a variable's value is empty...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tempe1109
Forum Newbie
Posts: 1
Joined: Mon Jun 08, 2009 11:47 am

If a variable's value is empty...

Post by tempe1109 »

I've inherited some code that uses urchin to store things in the database. The following gets the data:

Code: Select all

$getVar = "?utm_source=".@$_REQUEST["utm_source"]."&utm_medium=".@$_REQUEST["utm_medium"]."&utm_campaign=".@$_REQUEST["utm_campaign"];
and then later $getVar is used to form the URL string:

Code: Select all

$strBlocks .= "<a href='blocks.php".$getVar."&pg=1'><span class='paginator'>First</span></a>&nbsp;";
I want the code to leave the utm_source, utm_medium and utm_campaign off of the URL if the variables are empty.

What is the easiest way to do that?

Thanks!
Last edited by Benjamin on Mon Jun 08, 2009 1:08 pm, edited 1 time in total.
Reason: Changed code type from text to php.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: If a variable's value is empty...

Post by Christopher »

Something like:

Code: Select all

$getVar = '';
if (isset($_REQUEST['utm_source'])) {
     $getVar .= "utm_source={$_REQUEST['utm_source']}&";
}
...
(#10850)
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: If a variable's value is empty...

Post by McInfo »

This is meant to be a demonstration script, not a plug-and-pray.

Code: Select all

<?php
// Sends a plain text header so the output will be easy to debug
header('Content-Type: text/plain');
 
// Initializes an array to hold the URL arguments
$args = array();
 
// Loops through an array containing $_REQUEST indexes
foreach (array('utm_source', 'utm_medium', 'utm_campaign') as $arg) {
   
    // Checks if the element is not empty
    if (!empty($_REQUEST[$arg])) {
       
        // Adds an argument to the array in the form "name=value"
        $args[] = $arg.'='.$_REQUEST[$arg];
    }
}
 
// Adds another argument
$args[] = 'pg=1';
 
// Joins the arguments together with an ampersand "name1=value1&name2=value2"
echo "<a href='blocks.php?".implode('&', $args)."'><span class='paginator'>First</span></a>&nbsp;";
?>
Edit: This post was recovered from search engine cache.
Post Reply