If we have enough familiarity with PHP inbuilt string and array functions, then, it will more helpful while doing code on PHP. In this series, we have seen some of such functions already, like, trimming, PHP functions for string case conversions and etc. And, recently, we have seen about how to extract part of an input string using PHP.
In PHP, there is no inbuilt function for concatenating more than one string, as like as, strcat() of C, concat() of MySQL and etc. Even though, it is a very easy job, with the use of PHP operator which is especially for string concatenation. It is the very familiar dot(.) operator, that we have used in many examples.
For example, the dot operators are used to separate PHP variables from a hard-coded string, and to concatenate HTML tags with those variables, which is to be displayed to the browser as shown in the following code samples.
<?php
$table_name = "toys";
$query = "SELECT * FROM " . $table_name;
// (AND)
$heading = "PHP String Functions";
$heading_style = "<b>" . $heading . "</b>";
?>
Though PHP doesn’t have any inbuilt functions for concatenating strings, we can use PHP implode() function for this purpose, where this function is especially for joining an array of values together, and they will be separated with the given delimiter. Let us see about these two method on PHP string concatenation with suitable examples.
The following PHP program uses the dot operator to add a prefix for each element of the $table_name_array given. Then, by iterating over the $table_name_array variable, each of its elements will be concatenated with the given string initialized for $table_prefix variable.
<?php
$table_prefix = "tbl";
$table_name_array = array(
"user",
"student",
"event",
"task"
);
foreach ($table_name_array as $key => $value) {
$table_name_with_prefix[] = $table_prefix . $table_name_array[$key];
}
print "<PRE>";
print_r($table_name_with_prefix);
print "</PRE>";
?>
On executing the above PHP script, it will print new array elements to the browser which contain the prefixed table names after string concatenation.
Though PHP implode() functions are not dedicated for concatenation operation, we can use this optionally. Let us use this function to concatenate elements of the array $table_name_array, which we have seen in the above example.
<?php
$table_name_array = array(
"user",
"student",
"event",
"task"
);
foreach ($table_name_array as $key => $value) {
$table_name = implode($table_name_array);
}
print $table_name;
?>
For concatenating the string elements of the given input array without any delimiter, we have omitted this optional argument for the PHP implode() function.
Hi Vincy, I am a beginner in PHP and your tutorials are simple and easy to understand. This tutorial on String concatenation is easy to follow. Thanks, keep writing more.