Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a string with 5 php variables

Just think we need to echo a string something similar to this

sring01, sring02.<br />
sring03, sring04.</br />
sring05. 

all string come from variables. It is not important to have true values for all five variable. if they have false or empty output string should be different from above. just assume we have 2 empty variable for string02 and string03, then output should be

sring01, sring04.</br />
sring05.

Can anybody tell me what is the best way to achieve this?

I just tried it something like this but it doesn't work for me if not all variables true.

if($addressOne||$addressTwo||$city||$province||$country) {
    $location  = "$addressOne, $addressTwo.<br />";
    $location .= "$city, $province.<br />";
    $location .= "$country";
} else {
    $location = "some text";
    }
like image 321
TNK Avatar asked Sep 07 '13 07:09

TNK


People also ask

How do you create a string in PHP?

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string in PHP. For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use double backslash (\\).

What is $$ in PHP?

PHP | $ vs $$ operator The $ operator in PHP is used to declare a variable. In PHP, a variable starts with the $ sign followed by the name of the variable. For example, below is a string variable: $var_name = "Hello World!"; The $var_name is a normal variable used to store a value.

How do I cast a string in PHP?

The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string. We cannot use strval() on arrays or on object, if applied then this function only returns the type name of the value being converted. Return value: This function returns a string.


1 Answers

1.place all variable in a single array variable as elemnets like this 2.Then filter array for false values using this array function 3. Then chunk the filtered array using

$array = array($var1, $var2, $var3, $var4, $var5); //place all variables in an array

$filtered = array_filter($array); //Filter all false values such as '', null, FALSE

$chunk = array_chunk($filtered, 2); //Chunk whole array to smaller groups with 
                                    //atmost 2 elements
$data = '';
   foreach($chunk as $value)
   {
      $data .= implode(',', $value) . '<br/>';  //Then join two elements with ',' symbol
   }
echo $data;
like image 198
gvgvgvijayan Avatar answered Oct 28 '22 16:10

gvgvgvijayan