php constants and operators

Constants

Constants are like variables as they also store values but once they are defined they cannot be changed. A constant is basically a name for a value. The value cannot be changed during the script.

Syntax

define(name, value, case-insensitive)  

To create a php constant use define function. Default case-insensitive is false.

	<?php
	define("GREETING", "Welcome to webtrickshome.com");
	echo GREETING;
	?>

Here's an example of case-insensitive constant.

	<?php
	define("GREETING", "Welcome to webtrickshome.com", true);
	echo greeting;
	?>  

Constants are automatically global and can be used across the entire script. The example below uses a constant inside a function, even if it is defined outside the function:

<?php
function myTest() {
echo GREETING;
}

myTest();
?>        

Operators

Operators are used to perform operations on variables and values. PHP divides the operators in the following groups.

Arithmetic operators

Assignment operators

Comparison operators

Increment/Decrement operators

Logical operators

String operators

Array operators

Comparison Operators

Comparison operators are useful to compare two values. It returns boolean value true or false.

Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y

Use of Comparison Operators

$a = 10; 
$b = 20;

var_dump($a>$b);

if($a>b){
	echo 'YES';
}else{
	echo 'NO';
}

In a form, we are asking for a couples' number of child to be filled but one of them have no child. So, they'll enter 0 and in php 0 and false means empty and the form won't be submitted if we added the code for the form to be submitted only after all the input fields are filled. In such cases, we need to use (===) to check data if it's actually empty or not.

Example

$childCount = (int)"0";
if(empty($childCount)){
	echo 'Please enter the number of childs.'
}
$childCount = (int)"0";
if($childCount === ""){
	echo 'Please enter the number of childs.'
}

if($childCount === false){
	echo 'Please enter the number of childs.'
}

Assignment Operators

The assignment operators are used to define a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
x .= abc x = abc.def Concatenate
$a = 10;
$a = $a + 20 // $a += 20
$string = 'a quick brown fox';
$string .= ' jumps over the lazy dog';
echo $string;

Result: a quick brown fox jumps over the lazy dog

$q = true;
$query = "SELECT * FROM tbl_posts";
if($q == "true"){
	$query.= "WHERE id =".$q;
}
echo $query;

Result: "SELECT * FROM tbl_posts WHERE id =" .$q

Arithmatic Operators

The PHP arithmetic operators are used to perform arithmetical operations o data such as addition, substraction, multiplication, etc.

Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power (Introduced in PHP 5.6)

Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value while the decrement operators are used to decrement a variable's value.

Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
$a = 10;
echo ++$a;
echo --$a;

Result: 11

Result: 9

Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

AND - all the stated conditions must return true value

OR - one among the given conditions must be true

! - flips true to false or vice versa

$eng = 70;
$math = 50;
$science = 80;
 if ( $eng>=40 && $math >= 40 && $science >= 40 ){
 echo 'passed';
}else{
	echo 'failed';
}
$ram = 70;
$shyam = 39;
$hari = 20;
 if ( ($ram>=40) && ($shyam >= 40) && ($hari >= 40) ){
 echo 'Party';
}else{
	echo 'Study';
}

It's a good practice to wrap conditons with small braces while stating multiple conditions.

Ternary Operator

Ternary operator is a shorthand for if else statement. It can be used for single if else statement.

(boolean condition) ? 'action if true' : 'action if false';
echo ($a == 100 ) ? 'YES' : 'NO';

Concatenation Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

We can concatenate multiple strings in echo funtion using a (.).

$a = "ram";
$b = "shyam";
echo $a . $b;

Variables inside double quotes will be recognized by php but any variable inside single quotes will be assumed as charactes so we need to remove the variable from single quotes and concatenate it in such cases or use double quotes.

Examples

$b = 30;
Incorrect 
echo 'My age is $b'; Result -> My age is $b
Correct
echo "My age is $b"; Result -> My age is 30
Correct 
echo 'My age is' . $b; Result -> My age is 30

If you want to use double quotes, still a good practice would be to wrap variables with curly braces. This will allow us to add characters with the variable.

echo "My age is {$b}"; Result -> My age is 30
echo "I'm in my {$b}s"; Result -> I'm in my 30s.
echo "I'm in my $bs"; Result -> Undefined variable bs in line .............

Array Operators

The array operators are used to compare arrays.

Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identical $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identical $x !== $y Returns true if $x is not identical to $y

Error Suppressing Operator (@)

Error supressing is crucial in production environment. There's no point in displaying php error messages to the clients, it's useful to the developers only. Adding @ in php supresses the errors.

If any error appears while executing a code in php, read it, understand it and try to solve it. This way, you can learn php much better.

Types of error in php

Fatal error, exception, warning, notice. If fatal error occurs in any line of your php file, no codes below that line number will be executed. In other cases, rest of the codes will also be executed. We can disable those errors for production environment but need to see them in development environment.

$a;
if(@is_null($a)){
	echo 'yes';
}else{
	echo 'no';
}

Function error_reporting(0) is the best way to disable error reporting in production environment rather than adding suppressor at each block of codes.

Date and Time operator

Php has multiple functions to retrieve date and time.

time(); -> fetches current timestamp.

mktime(); -> maketime -> converts given time to timestamp

strtotime(); -> converts string to timestamp

Example

$now = time(); //current timestamp
echo $now;

Example

$time = mktime(12,11,22,11,23,2012);
echo $time;

Example

$strtime = strtotime('now'); 
$strtime = strtotime('+1 day'); 
$strtime = strtotime('+1 week');
echo $strtime;

Timestamp is the number of seconds since 00:00:00 1/1/1970. to convert timestamp into human readable format we can use date() or strftime().

$mktime = mktime(12,11,22,11,23,2012);	
echo date('l M jS \of Y',$mktime);

If the second parameter is not passed, date function will print current time.

echo date('H : i : s') will print current time. To store date in mysql you should use ymdhis

Local time

Local time can be printed in php using the function date_default_timezone_get(). If you don't have your default time zone correct either you can go to xampp configuration and open php.ini search for date.timezone and change it to your timezone as defined by php or you can set date_default_timezone_set() in your php file and set your runtime timezone. Changing server configuration permanently changes your timezone.

Type casting and type juggling

Typecasting allows us to change data type from string to integer or vice versa. When a value is processed through forms it will be saved as a sring even though you passsed a number. In such cases you might need to change its type. Typejuggling is the typecasting function performed automatically by php in some cases as shown below.

$a = "10";
$b = "20";
echo ($a + $b);

Result -> 30

Although there are string values, php assumes these numeric values as integer and performs mathematical operation in these cases.

$a = "10";
$b = "20 cars";
echo ($a + $b);

Result -> 30

Since there is a mathematical operator in the middle of the strings, php searches for numeric values in the variables and if found will perform the operation.

To see the data type of any variable.

echo gettype($a);

Result -> string

To typecast string to integer

settype($a,'int');
echo gettype($a); 

Result->integer

settype($a,'boolean');
echo gettype($a);

Result->boolean

Another Typecasting Method

$x = (bool)$a;
echo gettype($a); 

Result->boolean


0 Like 0 Dislike 0 Comment Share

Leave a comment