Page 1 of 1

If a variable's value is empty...

Posted: Mon Jun 08, 2009 12:08 pm
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!

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

Posted: Mon Jun 08, 2009 1:12 pm
by Christopher
Something like:

Code: Select all

$getVar = '';
if (isset($_REQUEST['utm_source'])) {
     $getVar .= "utm_source={$_REQUEST['utm_source']}&";
}
...

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

Posted: Mon Jun 08, 2009 1:30 pm
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.