简体   繁体   中英

PHP" How to include '-' only when variable exist?

$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

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";
  • Check if the variables are set with isset()
  • If so, add them to an array
  • Since number is a fixed string that you want, add it to the array
  • implode() the array joining with - to use in the URL

You could replace isset() with !empty() but 0 is considered empty so it would not be usable in the URL.

Use isset() if both exists then build the string

if (isset($type, $q)) {
  $result = $type .'-'. $q;
{

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";

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';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM