PHP String
In PHP, string is a sequence of individual characters and surrounded by single or double quotes. You can define a string in PHP as follows:
<?
$str = "This is a string in PHP";
$str2 = 'PHP string can be surrounded by single quotes';
?>
PHP string is very flexible. You can insert variables into a string using double quotes. At the runtime, the variable is evaluated as string; for example:
<?php
$str = "Morning";
$greeting = "good $str";
echo $greeting; // good morning
?>
You cannot insert variables into string with single quotes. So next time if you have a string which does not have any variable inside, you should define it with single quotes. At runtime PHP does not have to parse the string to find variables and evaluate it. By doing so, the performance of code is increased as well.
Compare strings
PHP provides you two built-in functions to compare strings, one with case-sensitive and the other is case-insensitive. These functions are strcmp($str1,$str2) and strcasecmp($str1,$str2) . These two functions return an integer value. If the value is zero means two string are the same otherwise they are not. Let's take a look an example of using string comparison functions:
<?php
$str1 = 'PHP';
$str2 = 'php';
$result = strcasecmp($str1,$str2);
if(!$result){
echo 'Match with strcasecmp';
}
else{
echo 'Not match with strcasecmp';
}
$result = strcmp($str1,$str2);
if(!$result){
echo 'Match with strcmp';
}
else{
echo 'Not match with strcmp';
}
?>
String Concatenation
Concatenation combines two or more strings or variables into one string. PHP allows you to concatenate strings by using a period (.). If you concatenate string with a variable which is not a string, the result is string as well. In this case, the variable is evaluated as a string. This is an example of using string concatenation:
<?php
$str = 'this is' . ' a string';
echo $str;
$x = 30;
$str = 'years old';
$str2 = 'Are you ' . $x . ' ' . $str;
echo $str2;
?>