skip to Main Content

Hello i have a basic question.
I get 4 variables from a html formular: $var1, $var2, $var3, $var4
I want to put them in one string $string but sometimes not all variables are set but i want a seperator like "/".

Example:
$var1 = "I"
$var2 = "was"
$var3 = "not"
$var4 = "here"
Example one: 
$string = $var1."/".$var2."/".$var3."/".$var4;
$string = I / was / not / here;
Example two:
$string = $var1."/".$var2."/".$var3."/".$var4;
$string = I / was /  / here;

Can someone help me with the extreme basic question?
Thanks

2

Answers


  1. You could put the data in an array, filter out nulls, and join to a string:

    $var1 = "I";
    $var2 = "was";
    $var3 = null;
    $var4 = "here";
    
    $vars = array_filter(array($var1, $var2, $var3, $var4));
    $string = join(" / ", $vars);
    
    Login or Signup to reply.
  2. Try implode() on an array:

    $all = [];
    $all[] = $var1;
    $all[] = $var2;
    $all[] = $var4;
    
    $string = implode('/',$all);
    echo $string;
    

    When a variable is not set, just do not put in the array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search