Monday, 2 September 2019

PHP Multi-line string

There is two way to handle PHP multi-line string either use concatenation or PHP heredoc.

PHP String Concatenation

The PHP has two string concatenation operators. The first operator ('.'), combines two or more than two string values into one string. While the second concatenating assignment operator (‘.=‘), which is mostly used multi-line string concatenation.

Code #1


    $firstName="John";
    $lastName="Doe";
    echo $firstName." ".$lastName;

Result:

John Doe

Code #2

    
    $str ="Hello";
    $str .= " World!";
    echo $str;

Result:

Hello World!

PHP Heredoc

PHP heredoc syntax: start with "<<<" after the operator provides an identifier, then newline and put your multi-line string and then the same identifier with a semicolon (;). Php heredoc Behave like a double-quoted without putting double quotes start and end of the string. It is very useful while we have a multi-line string and clean way rather than concatenating.

Code #1


    $str=<<<EOF
Hello World!
EOF;
    echo $str;

Result:

Hello World!

Code #2


    $str=<<<EOF
SELECT * from t1 where
id = 1 and status = 1 
EOF;
    echo $str;

Result:

SELECT * from t1 where id = 1 and status = 1

0 comments:

Post a Comment