w3resource

PHP: Constants

Description

A constant is an identifier for a simple value. The value cannot be modified during the script's execution. A valid constant name starts with a letter or underscore (no dollar($) sign before the name) and by convention constant identifier are always uppercase.

Constants are defined by using the define() function or by using the const keyword outside a class definition as of PHP 5.3.0. The name of the constant and the value must be placed within the parentheses. After defining it can never be changed or undefined. Only scalar data i.e. boolean, integer, float and string can be contained in constants.

PHP valid and invalid constant names

<?php
//Valid constants name
define("COUNTRY_NAME", "India");
define("CITYNAME", "New Delhi");
define("2NO_OF_STUDENTS", 60);
?>

Example of a PHP constant

<?php
define("COUNTRY_NAME", "India");
echo COUNTRY_NAME;
?>

Output :

India

View this example in browser

Previous: NULL
Next: PHP Operators Arithmetic Operators



PHP: Tips of the Day

Concatenation Operators: You can use concatenation to join strings "end to end" while outputting them (with echo or print).

You can concatenate variables using a . (period/dot).

Example:

<?php
// String variable

$name = 'Jhon';

// Concatenate multiple strings (3 in this example) into one and echo it once done.

echo '<p>Hello ' . $name . ', Nice to meet you.</p>';

// Concatenation Operators
?>

Output:

<p>Hello Jhon, Nice to meet you.</p>

Similar to concatenation, echo (when used without parentheses) can be used to combine strings and variables together (along with other arbitrary expressions) using a comma (,).

<?php
$itemCount = 1;
echo 'You have learn ', $itemCount, ' Tips', $itemCount === 1 ? '' : 's';
?>

Output:

You have learn 1 Tips

String concatenation vs passing multiple arguments to echo

Passing multiple arguments to the echo command is more advantageous than string concatenation in some circumstances. The arguments are written to the output in the same order as they are passed in.

echo "The total is: ", $x + $y;

The problem with the concatenation is that the period . takes precedence in the expression. If concatenated, the above expression needs extra parentheses for the correct behavior. The precedence of the period affects ternary operators too.

echo "The total is: " . ($x + $y);