Reputation:
$url = 'http://www.example.com/'.$type.$q.'number-'.$L.','.$country.'.html
If either $type
or $q
exist include -
after them, example:
$type = 1
$q = 2
http://www.example.com/1-2-number-fl,us.html
but when for example when $type
not exist to be:
http://www.example.com/2-number-fl,us.html
UPDATE: How if $type = 1- or $q = 1- then your could should prevent this to happen: http://www.example.com/1--2--number-fl,us.html
Upvotes: 1
Views: 71
Reputation: 3879
First check if the variables are set and they are not null. Add '-' to each variable.
$url = 'http://www.example.com/'.$type.$q.'number-'.$L.','.$country.'.html';
// declare a variable
$result = '';
// check for the variable type and add '-'
if(isset($type) && ($type!='')){
$result=trim($type,'-').'-';
}
// check for the variable q and add '-'
if(isset($q) && ($q!='')){
$result.=trim($q,'-').'-';
}
$url = 'http://www.example.com/'.$result.'number-'.$L.','.$country.'.html';
Upvotes: 0
Reputation: 344
It's important to check that $type and $q are not empty -- it's not enough to simply check that they are set. You also need to cover the case where the values are the integer 0 as PHP considers 0 to be an empty string, which causes empty( 0 ) to return true.
You could go with something like this:
if ( ((int) $type !== 0 && !empty( $type )) && ((int) $q !== 0 && !empty( $q ))) {
$result = $type . '-' . $q;
}
elsif ((int) $type !== 0 && !empty( $type )){
$result = $type;
}
else {
$result = $q;
}
$url = "http://www.example.com/{$result}-number-{$L}{$country}.html";
Upvotes: 0
Reputation: 79004
Another way:
if(isset($type)) { $array[] = $type; }
if(isset($q)) { $array[] = $q; }
$array[] = 'number';
if(isset($L)) { $array[] = $L; }
$url = "http://www.example.com/".implode('-', $array).",$country.html";
isset()
number
is a fixed string that you want, add it to the arrayimplode()
the array joining with -
to use in the URLYou could replace isset()
with !empty()
but 0
is considered empty so it would not be usable in the URL.
Upvotes: 2
Reputation: 101
check isset()
if(isset($type))
http://www.example.com/1-2-number-fl,us.html
else
http://www.example.com/2-number-fl,us.html
Upvotes: -1
Reputation: 133380
Use isset() if both exists then build the string
if (isset($type, $q)) {
$result = $type .'-'. $q;
{
Upvotes: 0