johanpw
johanpw

Reputation: 647

Simplify if-statements in PHP

Is it possible to simplify a series of if statements in PHP that I use to build a URL parameter? And how would I add a ? before the first parameter, and & to the rest, given that $var1 might be 0 too?

Here's an example of what I want to do:

<?php 
$var1 = 1;
$var2 = 1;
$var3 = 0;
$var4 = 1;

$urlparam = "";
if ($var1 == 1) $urlparam = $urlparam . "?var1=".$var1;
if ($var2 == 1) $urlparam = $urlparam . "&var2=".$var2;
if ($var3 == 1) $urlparam = $urlparam . "&var3=".$var3;
if ($var4 == 1) $urlparam = $urlparam . "&var4=".$var4;

echo "http://example.com/index.php" . $urlparam;
// http://example.com/index.php?var1=1&var2=1&var4=1
?>

Upvotes: 2

Views: 156

Answers (1)

John Conde
John Conde

Reputation: 219794

$vars = array(
    'var1' => 1,
    'var2' => 1,
    'var3' => 0,
    'var4' => 1
);
$vars = array_filter($vars);
$urlparam = '?' . http_build_query($vars);
  1. $vars holds an array of the values we may want to put in our querystring
  2. array_filter() removes any with a zero (false) value
  3. Use http_build_query() to build our querystring for us using the remaining values

Upvotes: 6

Related Questions