Home > Enterprise >  How to string two variables together in php
How to string two variables together in php

Time:12-03

I am new to php. And string concatenation is difficult for me. I want to concatenate the following string:

$branch = 'apple';
$rules = "(product=='iphone')andManufacturer==".$branch;
// result "(product == 'iphone')andManufacturer ==apple"

But the string I want:

"(product=='iphone')andManufacturer=='apple'"

Thanks.

CodePudding user response:

Try this(Added single quote to the string):

$branch = 'apple';
$rules = "(product=='iphone')andManufacturer=='".$branch."'";
echo $rules;

Another solution(Wrap the single quotes in double quotes to branch variable):

$branch = "'apple'";
$rules = "(product=='iphone')andManufacturer==".$branch;
echo $rules;

OUTPUT:

(product=='iphone')andManufacturer=='apple'

CodePudding user response:

You can directly put your $branch variable in "" quotes, no need for concatenation.

$branch = 'apple';
$rules = "(product=='iphone')andManufacturer=='$branch'";
echo $rules;

OR

$branch = "'apple'";
$rules = "(product=='iphone')andManufacturer==" . $branch;
echo $rules;

OUTPUT:

(product=='iphone')andManufacturer=='apple'

CodePudding user response:

You can check functions like sprintf() and printf()

$rules = sprintf("(product=='iphone')andManufacturer=='%s'", $branch); 
  •  Tags:  
  • php
  • Related