Posts Tagged ‘PHP’

We have been using the print and echo statements in our previous posts right? We know these two are used to print. But what are they actually? These are in-built functions. When we include a print statement in our script, we are actually “calling” the in-built function print. Similarly, a user can define his/her own functions, called user-defined functions.

Functions are the block of statements that can be used repeatedly in a script. These lines will be executed only upon a  “call” to the function.

User defined function :

Function declaration starts with the keyword “function” followed by function name. A function name can start with a letter or underscore and are case-insensitive.

Syntax :

function functionName() {
//code to be executed
}

1. Simple php function.
Lets write a simple php function.


<?php
//simple function.
function printMessage() {
echo "Ahoy!!";
}

printMessage(); // call the function.
?>

2. Function with arguments.

Arguments are like variables. Their scope is limited only to that particular function to which they have been passed. Passing the arguments is nothing but passing the information. Arguments are specified after the function name, inside the parentheses. A number of arguments can be passed each one separated  by a comma. The following example illustrates the function with a single argument.


<?php
//function with arguments.
function printMessageArg1($name) {
echo "$name";
}

printMessageArg1("Adonis"); // call the function.
?>

3. Function with default arguments value.

You can give your arguments a default value, like so :


<?php
//function with default arguments value.
function printMessageArg2($age=20) {
echo "your age is $age";
}

printMessageArg2(30); // call the function.
echo "<br>";
printMessageArg2(); // call the function. No value is passed, hence will take the default value specified.
?>

4. Function with return values.

You can make your function pass some information to the called function, using the keyword “return“. This value is called return value. The following function computes the sum of two numbers and returns the same to the called function :


<?php
//function with return values.
function retSum($x=0,$y=0) {
$z=$x+$y;
return $z;
}

$a=retSum(2,3); // call the function.
echo "$a<br>";
$a=retSum(3.57,66.3344); // call the function.
echo "$a<br>";
$a=retSum(); // call the function.
echo "$a<br>";
?>

When the same block of code has to be repeated over and over again, say for ‘N’ times, we can write the block of code ‘N’ times. But still we don’t want to do this (even though we are experts in ctrl-c and ctrl-v). That’s because computers are here to reduce our work right? So, we just want to make the best use of our computers.

In PHP, we have the following looping statements :

1. while : As long as the condition specified is true, execute a block of code.

while (condition) {
//code to be executed
}


<?php

//1. while loop.
echo "<strong>1. while loop.</strong><br>";
$x=0;
while ($x<=5) {
echo "\$x : $x <br>";
$x++;
}

?>

2. do… while : The condition is checked after executing the block of code once, and loops through the block of code until the specified condition is true.

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


<?php

//2. do...while loop.
echo "<br><br><strong>2. do...while loop.</strong><br>";
$x=0;
do {
echo "\$x : $x <br>";
$x++;
} while ($x==5);

?>

3. For loop : for loop can be used when you know beforehand how many times a block of code must be executed.

for (init counter; test counter; increment counter) {
//code to be executed
}


<?php

//3. for loop.
print "<br><br><strong>3. for loop.</strong><br>";
for ($x=0; $x<=5; $x++) {
echo "\$x : $x <br>";
}

?>

4. foreach loop : This loop works only on arrays. It is used to loop through each value in an array.

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


<?php

//4. foreach loop.
echo "<br><br><strong>4. foreach loop.</strong><br>";
$fruits = array("apple","mango","grape","cherry");
foreach ($fruits as $value) {
echo "$value <br>";
}

?>

Say you want to execute a block of code upon some condition, well, that’s were conditional statements comes handy.

PHP supports the following conditional statements :

1. if statement : Codes in the block (codes within {…}) are executed only if the specified condition is true.

if (condition) {
//codes to be executed.
}

<?php
//1. if statement.
echo "1. if statement.";
echo "<br>";
$x=10;
if ($x > 0) {
echo "This is true <br>";
}
?>

2. if… else statement : Execute one of the block. Block1 if the condition is true. Block2 if the condition is false.

if (condition) {
//codes to be executed.
}
else {
//codes to be executed.
}

<?php
//2. if... else statement.
echo "2. if... else statement.";
echo "<br>";
$x=2013;
if ($x == 2013) {
echo "We are in 2013 <br>";
}
else {
echo "We are not in 2013 <br>";
}
?>

3. if…elseif…else statement : Select one of the blocks to be executed out of many.

if (condition) {
//codes to be executed.
}
elseif {
//codes to be executed.
}
.
.
.
else {
//codes to be executed.
}

<?php
//3. if...elseif...else statement.
echo "3. if...elseif...else statement. <br>";
$mood = "boring";
if ($mood == "sleepy") {
echo "Save the code, and go to sleep <br>";
}
elseif ($mood == "boring") {
echo "Go browse something fun and get back <br>";
}
else {
echo "continue...";
}
?>

4. Switch statement : Select one of the blocks to be executed out of many.

switch (pattern) {
case label1 :
//execute the codes in here if label1==pattern.
break;
case label2 :
//execute the codes in here if label2==pattern.
break;
.
.
.
case labelN :
//execute the codes in here if labelN==pattern.
break;
default :
//execute the codes in here if none of the above label’s match the pattern.
}

<?php
//4. Switch statement.
echo "4. Switch statement. <br>";
$language = "php";
switch ($language) {
case "perl":
echo "We are coding using perl";
break;
case "python":
echo "we are coding using python";
break;
case "javascript":
echo "we are coding using javascript";
break;
default:
echo "We are coding using php";
}
?>

4. PHP – Operators.

Posted: September 20, 2013 in Hypertext Preprocessor (PHP)
Tags: ,

==>Arithmetic operators.

We can perform various arithmetic operations like addition (+), subtraction (-), multiplication (*), division (/) and modulus (%).
$variable (or a constant value) operator $variable (or a constant value).
Here is the code that demonstrates various arithmetic operations.

<?php
//Arithmetic operators.
echo "<strong>Arithmetic operations</strong> <br>";
$x=10.35;
$y=6;
echo "Additon <br>";
echo ($x + $y); //Addition.
echo "<br>Subtraction <br>";
echo ($x - $y); //Subtraction.
echo "<br>Multiplication <br>";
echo ($x * $y); //Multiplication.
echo "<br>Division <br>";
echo ($x / $y); //Division.
echo "<br>Modulus <br>";
echo ($x % $y); //Modulus.
?>

==>Assignment Operator.

We use ‘=’ to assign.
$variable = <value>
The example code :

<?php
//Assignment Operator.
echo "<br> <br><strong>Assignment operations</strong> <br>";
$x = $y;
echo "\$x has been assigned the value of \$y. Now \$x=$x";
?>

==>String Operators.

Concatenation : We use the dot (.) operator to achieve concatenation.
$variable (or a string).$variable (or a string)

<?php
//String Operators.
echo "<br> <br><strong>String operations</strong> <br>";
echo "Concatenation.<br>";
$a = "open ";
$b = "source";
$c = $a.$b; //concatenation.
echo "$c";
?>

==>Increment/Decrement Operators.

1. Pre-increment (++$variable).
2. Post-increment ($variable++).
3. Pre-decrement (–$variable).
4. Post-decrement ($variable–).

<?php
//Increment/Decrement Operators.
echo "<br> <br><strong>Increment/Decrement operations</strong> <br>";
echo "1.Pre-increment.<br>";
$x=0;
echo ++$x; // Pre-increment
echo "<br>2.Post-increment.<br>";
$y=0;
echo $y++; // Post-increment
echo "<br>3.Pre-decrement.<br>";
$z=10;
echo --$z; // Pre-decrement
echo "<br>4.Post-decrement.<br>";
$a=10;
echo $a--; // Post-decrement
?>

==>Comparison Operators.

1. Equal (==) :  Data types are not considered, just the values are considered.
2. Identical (===) : Data types are considered.
3. Not equal (!= ).
4. Not identical (!==).
5. Less than (<).
6. Less than or equal (<=).
7. Greater than (>).
8. Greater than or equal (>=).

<?php
//Comparison Operators.
echo "<br> <br><strong>Comparison operations</strong> <br>";
$x=2013;
$y="2013";
echo "1.Equal.<br>";
var_dump($x == $y); //Equal
echo "<br>2.Identical.<br>";
var_dump($x === $y); // Identical
echo "<br>3.Not equal.<br>";
var_dump($x != $y); // Not equal
echo "<br>4.Not identical.<br>";
var_dump($x !== $y); // Not identical
$a=5;
$b=10;
echo "<br>5.Greater than.<br>";
var_dump($a > $b); //Greater than
echo "<br>6.Less than<br>";
var_dump($a < $b); //Less than
?>

==>Logical Operators.

1. AND ($variable and $variable / $variable && $variable).
2. OR ($variable or $variable / $variable || $variable).
3. XOR ($variable xor $variable).
4. NOT (!$variable).

<?php
//Logical Operators.
echo "<br> <br><strong>Logical operations</strong> <br>";
$x=true;
$y=false;
echo "1.AND<br>";
var_dump($x && $y); // And
echo "<br>2.OR<br>";
var_dump($x || $y); // Or
echo "<br>3.XOR<br>";
var_dump($x xor $y); // Xor
echo "<br>4.NOT<br>";
var_dump(!$x); // Not
?>

==>Array operators.

1. Union (+) : Duplicates are removed.
2. Equality (==).
3. Identity (===).
4. Inequality (!=).
5. Inequality (<>).
6. Non-identity (!==).

<?php
//Array operators.
echo "<br> <br><strong>Array operations</strong> <br>";
$x = array("a" => "mango", "b" => "cherry");
$y = array("b" => "cherry", "c" => "apple");
$z = $x + $y; // union of $x and $y
echo "1.union<br>";
var_dump($z);
echo "<br>2.Equality<br>";
var_dump($x == $y);
echo "<br>3.Identity<br>";
var_dump($x === $y);
echo "<br>4.Inequality<br>";
var_dump($x != $y);
echo "<br>5.Inequality<br>";
var_dump($x <> $y);
echo "<br>6.Non-identity<br>";
var_dump($x !== $y);
?>

Constants :

Constants as the name indicates, as they are defined they cannot be changed during the script. A constant is an identifier. A valid constant starts with a letter of underscore, and are automatically global across the script. To set a constant, we use the function, define(). For an instance :

<?php
//Constants
define (“constnt”,”This is a constant and cannot be changed”);
echo constnt;
?>

Comments :

PHP supports three different types of comments.

  • Multi-line comment as in C.
    /*——–comment——–*/
  • Single-line comment (//) as in C and C++.
    //———comment———-
  • Single-line comment (#) as in Perl.
    #———comment———–

Here is the code to demonstrate the above :


<!DOCTYPE html>
<html>
<body>

<?php
//Constants
define ("constnt","This is a constant and cannot be changed");
echo constnt;

//Comments...

/*php
supports
multi-line
comment.
*/

//single-line comment.

#And also the single-line comment using #, as in perl.
?>

</body>
</html>

PHP supports various data types.

1. Integers : All natural numbers.

$x=34;

2. Floating point numbers : Fractional values.

$x=4.5;

3. Boolean : Boolean value can be either true or false.

$x=false;

4. Null : Null value specifies that the variable has no value.

$x=null;

5. Array : We can store multiple values using the array. Array values can be mixed, meaning, it can have integer value, floating point numbers, or strings.

$x= array(“Hello”, 2, 3.5);

6. String.

$x=”Ahoy!”;

Let us test these data types. Instead of using echo to print the values, let us use something called, var_dump. This prints both the data type as well as the value.

==>String Functions.

1. strlen() – Returns the length of the provided string.

echo strlen(“this line”);

2. strpos() – Returns the position of the character in the string or the stating position of the text in the string.

echo strpos(“lazy dog”,”dog”);


<!DOCTYPE html>
<html>
<body>

<?php
//Integer.
$x = 376;
var_dump ($x);
echo "<br>";

//float.
$x=3.4;
var_dump($x);
echo "<br>";

//boolean.
$x=true;
var_dump($x);
echo "<br>";

//Null.
$x=null;
var_dump($x);
echo "<br>";

//array.
$x=array("word", 2, 4.00, 'x');
var_dump($x);
echo "<br>";

//string.
$x="Ahoy!";
var_dump($x);
echo "<br>";

//---------------------------------------------------------------------------------------------------------
//string functions.

//1. strlen() - length of the string.
echo strlen ("This is a sentence.");
echo "<br>";
//2. strpos() - search a specified char or text within a string.
//This returns the position of the character specified, or starting
//position of the text specified.
echo strpos("Lazy dog","dog");

?>

</body>
</html>

1. PHP – Variables

Posted: September 9, 2013 in Hypertext Preprocessor (PHP)
Tags: ,

Well, in the previous PHP post, we created our first script. Lets dive in more…
I’m not going to explain the definitions and concepts in detail unless it is really necessary…

If you have coded in other programming languages like C, Perl etc, (assuming you have, without which you wouldn’t have ended here.) the rules for declaring a variable is pretty much the same. Just like shell scripting and Perl, a variable starts with ‘$’ symbol followed by the variable name. PHP is a loose type language, meaning no need to mention the data type before a variable as in C.

Variable declaration : $x;
Variable assignment : $x=10.99; $text=”RAndom”;

Lets see an example,

<?php
$x=5;
$y=10;
$z=$x+$y;
$name="Adonis";
echo $z;
echo "<br>";
echo $name;
?>

Screenshot from 2013-09-09 13:24:26

Lets save this file as, say prg1.php. Lets run it. Open your browser, type in the path. Mine, http://127.0.0.1/html/php/prg1.php
And you should be able to see something like this…

Screenshot from 2013-09-09 14:53:59

Alright. Now that the follow is achieved, from now on, I will be including just the source codes, no more screenshots. Saving and running is the same for all the rest of the codes.

Variable scopes :

Global : Available to all the functions.
Local : Available only to the function in which it was declared.
Static : Once a function is executed, its variables are deleted. If you want to use the variable(S) even after the function’s execution, you can use the keyword static while declaring a variable.

<!DOCTYPE html>
<html>
<body>

<?php
$x=5; //Global

function func1() {
$x=10; //local
echo "inside the function, x value : $x";
}

func1();

echo "<br>";
echo "outside the function, x value : $x";

//----------------------------------------------------------------

function func2() {
static $y=1; //variable will not be deleted.
echo "$y";
$y++;
}
//Lets check out our static variable...
echo "<br>";
func2();
echo "<br>";
func2();
echo "<br>";
func2();

?>

</body>
</html>