Using Constants and Variables to Add Functionality in PHP

Introduction

We have covered the basics of using the echo function to display text the way you want it. However, not use of constants and variables. A "Constant" is a placeholder that you reference within your code that is formally defined before using it. When naming a constant, remember they must begin with a letter or an underscore, and cannot begin with a number. Names are also case-sensitive. You define a value assigned to a constant with the PHP function define(). Once you define a constant, it cannot be changed or undefined.

Example

<html>

<head><title>First Program In PHP</title></head>

<body>

<?php

define ('name', 'PHP developer');

echo 'Sharad is a ';

echo name;

?>

</body>

</html>

 

A constant with the name name is set with the value "PHP developer" that can be recalled and displayed later. Although this constant cannot be changed or reset, it is available for use by any part of your script.

 

Output


Use-Constant-in-PHP.jpg

A "Variable" obviously is meant to be a variable; they are meant to change or be changed at some point in your program. Variables do not need to be defined or declared and can simply be assigned when needed. They act as a container that stores information for later use in your scripts, and the contents of them can be changed. Variables are denoted with a dollar($) sign and are case-sensitive (in other words, $date and $Date are different variables). The first letter of the variable name must be an underscore or letter, and cannot be a number.

 

Example

 

<html>

<head><title>First Program In PHP</title></head>

<body>

<?php

define('name', '.Net developer');

echo '<h2>Sharad is a </h2>';

echo name;

echo "<br>";

$sal=10000;

echo 'And his sallary is';

echo $sal;

?>

</body>

</html>

 

Output


use-Variable-in-php.jpg

 

The value 10,000 is assigned to the variable $sal. The number does not need to be quoted in the manner a string is. In fact, in the following, PHP would see the value of $sal as a string containing the character 10,000.

$sal= '10,000';

Keeping this value as an integer makes it much easier to perform mathematical calculations on it later on, such as giving the viewer the average sal. For example:

 

<?php

$hotsal = 10000;

$sal = 6000;

$mediumsal = 8000;

$trisal = 5000;

$avgsal = (($hotsal+$sal+$mediumsal+$trisal)/4);

echo 'The average sallary is ';

echo $avgsal;

?>

 

PHP also has numerous built-in mathematical functions that you can use on variables that contain numbers, such as:

rand([$min, $max])
Returns a random number
ceil($value)
Returns a next highest integer by rounding the value upwards
floor($value)
Returns a next lowest integer by rounding the value downwards
max($value[, $value2[, $...]])
Returns the largest value found in the set of supplied arguments
min($value[, $value2[, $...]])
Returns the smallest value found in the set of supplied arguments

Output


variable2-in-php.jpg