0% found this document useful (0 votes)
9 views

php_cookbook-13-20

PHP Book 3

Uploaded by

dhivakar.m23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

php_cookbook-13-20

PHP Book 3

Uploaded by

dhivakar.m23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PHP Programming Cookbook 4 / 63

Figure 1.2: XAMPP window after a successful installation with Apache and MySQL enabled

• Place your web project inside the htdocs directory. In the common case, if you installed XAMPP directly inside the C: drive
of your PC, the path to this folder would be: C:xampphtdocs

Figure 1.3: XAMPP Directory for Web Projects

To test the services are up and running you can just enter localhost in your address bar and expect the welcoming page.
PHP Programming Cookbook 5 / 63

1.3 PHP Language Basics

The aim of this section is to introduce the general syntax you should expect in PHP.

1.3.1 Escaping to PHP

There are four ways the PHP parser engine can differentiate PHP code in a webpage:

• Canonical PHP Tags

This is the most popular and effective PHP tag style and looks like this:
<?php...?>

• Short-open Tags

These are the shortest option, but they might need a bit of configuration, and you might either choose the --enable-short-
tags configuration option when building PHP, or set the short_open_tag setting in your php.ini file.
<?...?>

• ASP-like Tags

In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:
<%...%>

• HTML script Tags

You can define a new script with an attribute language like so:
<script language="PHP">...</script>

1.3.2 Commenting PHP

Just like other languages, there are several ways to comment PHP code. Let’s have a look at the most useful ones:
Use # to write single-line comments
<?
# this is a comment in PHP, a single line comment
?>

Use // to also write single-line comments


<?
// this is also a comment in PHP, a single line comment
?>

Use /* ...*/ to write multi-line comments


<?
/* this is a multi line comment
Name: Web Code Geeks
Type: Website
Purpose: Web Development
*/
?>
PHP Programming Cookbook 6 / 63

1.3.3 Hello World

The very basic example of outputting a text in PHP would be:


<?
print("Hello World");
echo "Hello World";
printf("Hello World");
?>

The result of the above statements would be the same: "Hello World". But why are there three different ways to output?

• print returns a value. It always returns 1.


• echo can take a comma delimited list of arguments to output.
• printf is a direct analog of C’s printf().

1.3.4 Variables in PHP

Any type of variable in PHP starts with a leading dollar sign ($) and is assigned a variable type using the = (equals) sign. The
value of a variable is the value of its most recent assignment. In PHP, variables do not need to be declared before assignment.
The main data types used to construct variables are:

• Integers - whole numbers like 23, 1254, 964 etc

• Doubles - floating-point numbers like 46.2, 733.21 etc


• Booleans - only two possible values, true or false
• Strings - set of characters, like Web Code Geeks

• Arrays - named and indexed collections of other values


• Objects - instances of predefined classes

The following snippet shows all of these data types declared as variables:
<?
$intNum = 472;
$doubleNum = 29.3;
$boolean = true;
$string = ’Web Code Geeks’;
$array = array("Pineapple", "Grapefruit", "Banana");

// creating a class before declaring an object variable


class person {
function agePrint() {
$age = 5;
echo "This person is $age years old!";
}
}
// creating a new object of type person
$object = new person;
?>
PHP Programming Cookbook 7 / 63

1.3.5 Conditional Statements in PHP

Conditional statements are used to execute different code based on different conditions.
The If statement
The if statement executes a piece of code if a condition is true. The syntax is:
if (condition) {
// code to be executed in case the condition is true
}

A practical example would be:


<?php
$age = 18;

if ($age < 20) {


echo "You are a teenager";
}
?>

Because the condition is true, the result would be:


You are a teenager

The If. . . Else statement


The If. . . Else statement executed a piece of code if a condition is true and another piece of code if the condition is false. The
syntax is:
if (condition) {
// code to be executed in case the condition is true
}
else {
// code to be executed in case the condition is false
}

An example of an If. . . Else statement would be:


<?php
$age = 25;

if ($age < 20) {


echo "You are a teenager";
}
else {
echo "You are an adult";
}
?>

Because the condition is false, the result in this case would be:
You are an adult

The If. . . Elseif. . . Else statement


This kind of statement is used to define what should be executed in the case when two or more conditions are present. The syntax
of this case would be:
if (condition1) {
// code to be executed in case condition1 is true
}
PHP Programming Cookbook 8 / 63

elseif (condition2) {
// code to be executed in case condition2 is true
}
else {
// code to be executed in case all conditions are false
}

Again, a simple example to demonstrate this:


<?php
$age = 3;

if ($age < 10) {


echo "You are a kid";
} elseif ($age < 20) {
echo "You are a teenager";
} else {
echo "You are an adult";
}
?>

The result, as you might expect, would be:


You are a kid

1.3.6 Loops in PHP

In PHP, just like any other programming language, loops are used to execute the same code block for a specified number of times.
Except for the common loop types (for, while, do. . . while), PHP also support foreach loops, which is not only specific to PHP.
Languages like Javascript and C# already use foreach loops. Let’s have a closer look at how each of the loop types works.
The for loop
The for loop is used when the programmer knows in advance how many times the block of code should be executed. This is
the most common type of loop encountered in almost every programming language.
for (initialization; condition; step){
// executable code
}

An example where we use the for loop would be:


for ($i=0; $i < 5; $i++) {
echo "This is loop number $i";
}

The result of this code snippet would be:


This is loop number 0
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4

The while loop


The while loop is used when we want to execute a block of code as long as a test expression continues to be true.
while (condition){
// executable code
}
PHP Programming Cookbook 9 / 63

An example where we use the while loop would be:


$i=0; // initialization
while ($i < 5) {
echo "This is loop number $i";
$i++; // step
}

The result of this code snippet would be just the same as before:
This is loop number 0
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4

To have a clearer idea of the flow of these two loops, look at the graphic below:

Figure 1.4: PHP for and while Loops

The do. . . while loop


PHP Programming Cookbook 10 / 63

The do...while loop is used when we want to execute a block of code at least once and then as long as a test expression is
true.
do {
// executable code
}
while (condition);

An example where we use the do. . . while loop would be:


$i = 0; // initialization
do {
$i++; // step
echo "This is loop number $i";
}
while ($i < 5); // condition

This time the first loop number would be 1, because the first echo was executed only after variable incrementation:
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4
This is loop number 5

The foreach loop


The foreach loop is used to loop through arrays, using a logic where for each pass, the array element is considered a value
and the array pointer is advanced by one, so that the next element can be processed.
foreach (array as value) {
// executable code
}

An example where we use the foreach loop would be:


$var = array(’a’,’b’,’c’,’d’,’e’); // array declaration

foreach ($var as $key) {


echo "Element is $key";
}

This time the first loop number would be 1, because the first echo was executed only after variable incrementation:
Element is a
Element is b
Element is c
Element is d
Element is e

1.4 PHP Arrays

Arrays are used to store multiple values in a single variable. A simple example of an array in PHP would be:
<?php
$languages = array("JS", "PHP", "ASP", "Java");
?>
PHP Programming Cookbook 11 / 63

Array elements are accessed like this: $arrayName[positionIndex]. For the above example we could access "PHP" this
way: $languages[1]. Position index is 1 because in programming languages the first element is always element 0. So, PHP
would be 1 in this case.
There are three types of arrays in PHP:
Indexed Arrays
We can create these kind of arrays in two ways shown below:
<?php
$names = array("Fabio", "Klevi", "John");
?>

<?php
// this is a rather manual way of doing it
$names[0] = "Fabio";
$names[1] = "Klevi";
$names[2] = "John";
?>

An example where we print values from the array is:


<?php
$names = array("Fabio", "Klevi", "John");
echo "My friends are " . $names[0] . ", " . $names[1] . " and " . $names[2];
?>

// RESULT
My friends are Fabio, Klevi and John

Looping through an indexed array is done like so:


<?php
$names = array("Fabio", "Klevi", "John");
$arrayLength = count($names);

for($i = 0; $i < $arrayLength; $i++) {


echo $names[$i];
echo "";
}
?>

This would just print the values of the array.


Associative Arrays
Associative arrays are arrays which use named keys that you assign. Again, there are two ways we can create them:
<?php
$namesAge = array("Fabio"=>"20", "Klevi"=>"16", "John"=>"43");
?>

<?php
// this is a rather manual way of doing it
$namesAge[’Fabio’] = "20";
$namesAge[’Klevi’] = "18";
$namesAge[’John’] = "43";
?>

An example where we print values from the array is:

You might also like