Artificial intelligence, robotics, PHP, Javascript, hacking, CSS, Photoshop, deep learning, machine learning, Visual basic

Friday, 10 August 2018

PHP (basic syntax)

PHP

A PHP scripts can be placed anywhere in the document. PHP scripts start with <?php and end with ?>

For example:
<?php
//PHP code goes here
?>

PHP documents has .php as a default file extension. A PHP file normally contains HTML tags and some PHP scripting code.

Basic syntax

Comments in PHP

A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read by someone who is looking at the code.
Comments can be used to:
  • Let others understand what you are doing
  • Remind yourself of what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. Comments can remind you of what you were thinking when you wrote the code
In PHP // as well as # is used for the single-line comment, and for the multiline comment block php use /* to start */.

Print statement
In PHP there are two basic ways to get the output: echo and print They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.

Echo statement
For example:
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ""string ""was ""made ""with multiple parameters.";
?>

Print statement
or example
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>

 Variables

Variables are the containers that contain the values. In PHP varibles are declared by using $ sign. Syntax:- $variable_name  = “value”;

Example:
<?php
$txt = 
"Hello world!";
$x = 
5;
$y = 
10.5;
?>

Rules for PHP variables:
  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)

 Operators

Operators are used to performing operations on variables and values.
PHP divides the operators into the following groups:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators

Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, 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)


Assignment Operators

The PHP assignment operators are used with numeric values to write 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


Comparison Operators

The PHP comparison operators are used to compare two values (number or string):
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

 PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP 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

 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

 String 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


Array Operators

The PHP 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

===
Identity
$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-identity
$x !== $y
Returns true if $x is not identical to $y

Function

A function is a reusable piece or block of code that performs a specific action.
Functions can either return values when called or can simply perform an operation without returning any value.
PHP has over 700 functions built in that perform different tasks
user-defined function declaration starts with the word function:

Syntax

function functionName() {
    code to be executed;
}

Example:
<?php
function writeMsg() {
    
echo "Hello world!";
}

writeMsg(); 
// call the function
?>

Decision-making statements

PHP decision making statements namely, ifelseelseif and switch.
PHP like most other programming languages lets us write conditional statements that help in making decisions.

if statement

The simplest decision-making statement to start with is the if statement.
if ( expression ) {
  //some code
}
 
//some more code goes here...
In the above code snippet, we have created an if statement. The code inside the if the block is executed only when the expression evaluated to true. Otherwise, it is ignored.
$x = 10;
 
if ( $x > 0 ) {
  echo "x is greater than 0.";
}
 
echo " Value of x = " . $x;
 
In the above code, the value of variable $x is 10 which is greater than 0 so, the code inside the if statement is executed.
The above code will print "x is greater than 0. Value of x = 10".
$x = 10;
 
if ( $x < 0 ) {
  echo "x is less than 0.";
}
 
echo " Value of x = " . $x;
 
In the above code, $x is not less than 0 so, the code inside the if statement is not executed.
The above code will print "Value of x = 10".

if...else statement

When looking for either-or option i.e., two paths we go for if...else statement.
if ( expression ) {
  //code inside if block
} else {
  //code inside else block
}
 
//some more code goes here...
We have created an if...else statement in the above code snippet. If the expression of the if statement evaluates to true, then the code inside the if block will be executed. Otherwise, the code inside the else block will be executed.
$x = 10;
 
if ( $x == 10 ) {
  echo "x is 10";
} else {
  echo "x is not 10";
}
 
echo "value of x = " . $x;
The above code will print "x is 10" and "value of x = 10".
$x = 5;
 
if ( $x == 10 ) {
  echo "x is 10";
} else {
  echo "x is not 10";
}
 
echo "value of x = " . $x;
The above code will print "x is not 10" and "value of x = 10".

elseif statement

If we want multiple options to choose from then we use the elseif statement.
if ( expression1 ) {
  //code inside if block
} elseif ( expression2 ) {
  //code inside 1st elseif block
} else {
  //code inside else block
}
 
//some more code goes here...
In the above code we have created an elseif statement to have more than 2 options. So, when we run the above code, first the expression of if will be evaluated and if it equals to true then the code inside the if block will be executed.
If it fails, then expression2 of the elseif will be evaluated. And if it is true then code inside the 1st elseif block will be executed.
If the 1st elseif fails then the code inside the else block will be executed.
$x = 10;
 
if ( $x < 0 ) {
  echo "x is negative.";
} elseif ( $x == 0 ) {
  echo "x is equal to 0";
} else {
  echo "x is positive";
}
 
echo " value of x = " . $x;
The above code will print "x is positive" and "value of x = 10".

switch statement

We use the switch statement to match a given expression with several different values.
switch ( expression ) {
  
  case 'value1' :
    //some code for value 1
    break;
 
  case 'value2' :
    //some code for value 2
    break;
 
  default:
    //some code for default
}
In the above code snippet, we have created a switch statement. The expression is matched with the value. Say, for example, the expression matches with value2 then, the code for that case block will be executed. If no match is found then the code inside the default block will be executed.
The default block is optional. We use the break keyword to come out of the switch block.
$x = 10;
 
switch ( $x ) {
  
  case 1:
    echo "x is 1";
    break;
 
  case 5:
    echo "x is 5";
    break;
 
  case 10:
    echo "x is 10";
    break;
 
  default:
    echo "x is something else";
 
}
 
echo " value of x = " . $x;
The above code will print "x is 10" and "value of x = 10";
The flow of the above code.
We have set the value of variable x to 10. Next, we are passing x as an expression to the switch block. So, the value of x (i.e., 10) is matched with the value of the three case. First, expression 10 is matched with value 1, but it fails. So, 10 is matched with value 5 and it fails too. Next, 10 is matched with value 10 of the third case and it is found to be equal. So, the code of the third case is executed and then we break out of the switch block. And then the last line is executed.

Matching multiple case value of switch statement

In the following example, the expression is matched with multiple case value.
switch ( expression ) {
  
  case 'value1' :
  case 'value2' :
  case 'value3'
    //some code1
    break;
 
  case 'value4':
  case 'value5':
    //some code2
 
  default:
    //some code for default
}
In the above code, the expression is first matched with value1value2, and value3. If anyone of them is equal to the expression then code1 is executed and we break out of the switch block.
Otherwise, we match expression with value4 and value5. If a match is found then code2 is executed and we break out of the switch block.
If none of the case value matches then, we execute the default code block.

Loop 

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
·        for − loops through a block of code a specified number of times.
·        while − loops through a block of code if and as long as a specified condition is true.
·        do...while − loops through a block of code once, and then repeats the loop as long as a special condition is true.
·        foreach − loops through a block of code for each element in an array.
We will discuss about continue and break keywords used to control the loops execution.

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.

Syntax

for (initialization; condition; increment){
   code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop −
<html>
   <body>
      
      <?php
         $a = 0;
         $b = 0;
         
         for( $i = 0; $i<5; $i++ ) {
            $a += 10;
            $b += 5;
         }
         
         echo ("At the end of the loop a = $a and b = $b" );
      ?>
   
   </body>
</html>

This will produce the following result −
At the end of the loop a = 50 and b = 25


The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

Syntax

while (condition) {
   code to be executed;
}


Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
   <body>
   
      <?php
         $i = 0;
         $num = 50;
         
         while( $i < 10) {
            $num--;
            $i++;
         }
         
         echo ("Loop stopped at i = $i and num = $num" );
      ?>
      
   </body>
</html>

This will produce the following result −
Loop stopped at i = 10 and num = 40 


The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax

do {
   code to be executed;
}
while (condition);


Example

The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10 −
<html>
   <body>
   
      <?php
      $i = 0;
         $num = 0;
         
         do {
            $i++;
         }
         
         while( $i < 10 );
         echo ("Loop stopped at i = $i" );
      ?>
      
   </body>
</html>

This will produce the following result −
Loop stopped at i = 10


The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value) {
   code to be executed;
}


Example

Try out following example to list out the values of an array.
<html>
 <body>
   
      <?php
         $array = array( 1, 2, 3, 4, 5);
         
         foreach( $array as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5


The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. It gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<html>
   <body>
   
      <?php
         $i = 0;
         
         while( $i < 10) {
            $i++;
            if( $i == 3 )break;
         }
         echo ("Loop stopped at i = $i" );
      ?>
   
   </body>
</html>

This will produce the following result −
Loop stopped at i = 3


The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement, the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.
<html>
   <body>
   
      <?php
         $array = array( 1, 2, 3, 4, 5);
         
         foreach( $array as $value ) {
            if( $value == 3 )continue;
            echo "Value is $value <br />";
         }
      ?>
   
   </body>
</html>

This will produce the following result −
Value is 1
Value is 2
Value is 4
Value is 5


Share:
Location: Delhi, India

0 comments:

Post a Comment

Copyright © Technotalk | Powered by Academy for brilliance