Learn PHP-19 : Concatenation Assignment Operators

Posted: November 14, 2010 in PHP
Tags:

The concatenation operator ( . ) returns the combined value of its right and left values. The variable’s data type has an affect on the output.

Here are code examples using the concatenation operator ( . ) to unite or combine variable values

<?php
echo "deve"."lop";          //displays "develop"
echo "<br /><br />";            // html line breaks

echo "deve" . "lop";        //displays "develop"
echo "<br /><br />";            // html line breaks

echo 4 . 3;                     //displays "43"
echo "<br /><br />";            // html line breaks

echo 4.3;                       //displays "4.3"
echo "<br /><br />";            // html line breaks

echo "4" . "3";                //displays "43"
echo "<br /><br />";            // html line breaks

echo '4' . '3';                  //displays "43"
?>

The concatenating assignment operator ( .= ), which appends the variable value on the right side to the variable on the left side. We use this method many times to compound and keep adding to one variable so it will retain its current value, and just append the new values onto the current value’s tail end.

Here is a code example using the concatenating assignment operator ( .= ) to append or compound values

<?php
$var1 = "Hello World!";
$var2 = "We are silly!";
$htmlOutput = ''; // set as empty, but defined

// notice the period before each ( = ) sign... that is concatenating them onto the original var value
$htmlOutput .= '<table bgcolor="#663366" cellpadding="8">';
$htmlOutput .= '<tr>';
$htmlOutput .= '<td bgcolor="#CCCCCC">';
$htmlOutput .= ' ' . $var1 . ' ';
$htmlOutput .= '</td>';
$htmlOutput .= '<td bgcolor="#FFFF00">';
$htmlOutput .= ' ' . $var2 . ' ';
$htmlOutput .= '</td>';
$htmlOutput .= '</tr>';
$htmlOutput .= "</table>";
// Now print or echo the output
echo "$htmlOutput ";
?>

The output is shown below :

Hello World! We are silly!
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s