Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Understanding String Literals and Operations

By: FYICenter.com

Part:   1  2  3   4 

(Continued from previous part...)

How To Concatenate Two Strings Together?

You can use the string concatenation operator (.) to join two strings into one. Here is a PHP script example of string concatenation:

<?php 
echo 'Hello ' . "world!\n";
?>

This script will print:

Hello world!

How To Compare Two Strings with Comparison Operators?

PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. Those operators use ASCII values of characters from both strings to determine the comparison results. Here is a PHP script on how to use comparison operators:

<?php
$a = "PHP is a scripting language.";
$b = "PHP is a general-purpose language.";
if ($a > $b) {
  print('$a > $b is true.'."\n");
} else {
  print('$a > $b is false.'."\n");
}
if ($a == $b) {
  print('$a == $b is true.'."\n");
} else {
  print('$a == $b is false.'."\n");
}
if ($a < $b) {
  print('$a < $b is true.'."\n");
} else {
  print('$a < $b is false.'."\n");
}
?>

This script will print:

$a > $b is true.
$a == $b is false.
$a < $b is false.

How To Convert Numbers to Strings?

In a string context, PHP will automatically convert any numeric value to a string. Here is a PHP script examples:

<?php 
print(-1.3e3);
print("\n");
print(strlen(-1.3e3));
print("\n");
print("Price = $" . 99.99 . "\n");
print(1 . " + " . 2 . " = " . 1+2 . "\n");
print(1 . " + " . 2 . " = " . (1+2) . "\n");
print(1 . " + " . 2 . " = 3\n");
print("\n");
?>

This script will print:

-1300
5
Price = $99.99
3
1 + 2 = 3
1 + 2 = 3

The print() function requires a string, so numeric value -1.3e3 is automatically converted to a string "-1300". The concatenation operator (.) also requires a string, so numeric value 99.99 is automatically converted to a string "99.99". Expression (1 . " + " . 2 . " = " . 1+2 . "\n") is a little bit interesting. The result is "3\n" because concatenation operations and addition operation are carried out from left to right. So when the addition operation is reached, we have "1 + 2 = 1"+2, which will cause the string to be converted to a value 1.

How To Convert Strings to Numbers?

In a numeric context, PHP will automatically convert any string to a numeric value. Strings will be converted into two types of numeric values, double floating number and integer, based on the following rules:

  • The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
  • If the valid numeric data contains '.', 'e', or 'E', it will be converted to a double floating number. Otherwise, it will be converted to an integer.

(Continued on next part...)

Part:   1  2  3   4 


Selected Developer Jobs:

More...