0% found this document useful (0 votes)
11 views19 pages

LAB C1 Introduction To PHP

PHP is an open-source, server-side scripting language designed for web development, allowing for dynamic page generation. It supports various databases and can be embedded in HTML, with a syntax similar to C and Java. The document also covers PHP's basic syntax, variable types, operators, and how to create and run PHP files using WAMP or XAMPP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views19 pages

LAB C1 Introduction To PHP

PHP is an open-source, server-side scripting language designed for web development, allowing for dynamic page generation. It supports various databases and can be embedded in HTML, with a syntax similar to C and Java. The document also covers PHP's basic syntax, variable types, operators, and how to create and run PHP files using WAMP or XAMPP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

PHP

1.0) Introduction
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. The goal of the language is to allow web developers to write
dynamically generated pages quickly. PHP runs on different platforms (Windows, Linux,
Unix, etc.). PHP is compatible with almost all servers used today. PHP is FREE to
download from the official PHP resource: www.php.net. The fundamental characteristics
of PHP are:

i. PHP stands for PHP: Hypertext Preprocessor


ii. PHP is a server-side scripting language, like ASP, JSP , Perl.
iii. PHP is server-side scripting language, which is used to manage the dynamic
content of the website.
iv. PHP scripts are executed on the http server
v. PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, SQL,
Generic ODBC, etc.)
vi. PHP can be embedded into HTML.
vii. PHP is a open source software that is free to download and use

1.1) How does it Work?


When a user navigates in her browser to a page that ends with a .php extension, the
request is sent to a web server, which directs the request to the PHP interpreter. As
shown in the diagram above, the PHP interpreter processes the page, communicating
with file systems, databases, and email servers as necessary, and then delivers a web
page to the web server to return to the browser.
1.3) PHP Requirements
To work with PHP one needs to have some supports. These are:
● Install Apache on your own server, install PHP, and MySQL (or Install WAMP or
XAMPP server to have both)
● Find a web hosting plan with PHP and MySQL support or use localhost in your
browser.
● Note pad/word pad or script editor such as PHP editor or other software
development tools such as Eclipse.

1.4) Basic syntax for PHP Coding


PHP's syntax and semantics are similar to most other programming languages like C,
Java, Perl etc. All PHP code is contained with a tag <? ... ?> or <?php ... ?> or , <script
language=”php”> ... </script>. The standard syntax of PHP tag is:

<?php
//your code here
?>

1.5) How to create and run a PHP file using WAPM or XAMPP.
The functional steps involved in creating and running a PHP program are as follows:
Step 1: Open a text editor (such as notepad) and create a simple PHP code.
<?php echo "Hello PHP Web Engineers!"; ?>
Step 2: Go to save as at file menu and save the file giving three parameters:
i) select web publishing folder/subfolder (htdocs folder in XAMPP or www
folder in WAMP server at the root).
ii) Give a file name with the extension .php and
iii) select “all types” at the file types.
Step 3: Run the XAMPP server and start the Apache and MySQL from its control panel.
Step 4: Open a browser and type “localhost/your_file_name.php” at the url address bar.
Press enter and you will see the output at the browser “Hello PHP Web
Engineers!”

1.6) Some important things to be considered in PHP script writing:


i) Case sensitivity: In PHP, keyword (e.g., echo, if, else, while), functions, user-defined
functions, classes are not case-sensitive. However, all variable names and data are
case-sensitive.

ii) Semicolon: Each PHP statement must be terminated by a semicolon “ ; ”.

iii) PHP comments: Single line or multiple line program comments are allowed in PHP
with the following syntax:
a) // this is a single line comment
b) # this is another single line comment
c) /* this is a php multi line comment
this is a php multi line comment
this is a php multi line comment */

iv) The $ symbol: One must prefix the $ symbol before the name of any declared
variable or array (details in next chapter “variable and arrary”).

v) PHP echo and print: PHP echo and print statements are used for display output.

vi) Embedded: PHP code can be easily embedded within HTML tags and script. The
following example will highlight on comments and embedment. Note that, though it is a
html code file saving process must follow 1.5: step 2.

code Result
<html> This is a html code
<head><title>HTML & PHP</title></head> This is a php code
<body>
Hello! I am the output of html code
<BR>
// First five lines are HTML code
<?php
print “Hi, I am PHP output”;
?>
# The red colored lines are PHP code
</body>
</html>
Variables and Data types
What Is a Variable?
A variable is a keyword or phrase that acts as an identifier for a value stored in a system’s
memory. This is useful because it allows us to write programs that will perform a set of actions on
a variable value, which means you can change the output of the program simply by changing the
variable, rather than changing the program itself. In PHP, you define a variable with the following
form: $variable_name = value;
Rules for variables
● The dollar sign ($) must always fill the first space of your variable
● The first character after the dollar sign must be a letter or underscore. It can't under any
circumstances be a number for example, a-z, A-Z, 0-9, and _.;
● Variables in PHP are case sensitive. This means that $variable_name and
$Variable_Name are different.
● Variables with more than one word should be separated with underscores; for example,
$test_variable.
● Variables can be assigned values by using the equals sign (=).
● Always end with a semicolon (;) to complete the assignment of the variable.
Type of Variables
PHP accepts nearly anything in a variable using one of the following data types:

1. String: Alphanumeric characters, such as sentences or names


2. Integer: A numeric value, expressed in whole numbers
3. Float: A numeric value, expressed in real numbers (decimals)
4. Boolean: Evaluates to TRUE or FALSE (sometimes evaluates to 1 for TRUE and 0 for
FALSE)
5. Array: An indexed collection of data (see the “Understanding Arrays” section later in
this chapter for more information on this subject)
6. Object: A collection of data and methods (see Chapter 4 and its section on PHP Data
Objects for more information on this subject)

1. String
A string is any series of characters enclosed in single (') or double (") quotes, or that you create
using special heredoc or nowdoc syntax.

a) Single-Quote String: Enclosing a string in single quotes is the simplest way to create a string
in PHP. It doesn’t expand special characters or variables. Ex.
<?php
$abc = 'It\'s cold outside today!';
echo $abc;
?>

b) Double-Quote String: Strings encased in double quotes behave similarly to strings encased in
single quotes but they interpret more special characters, including expanding variables.
<?php
$abc = 'It\'s cold outside today!';
echo $abc;
?>
c) heredoc string: PHP introduces a more robust string creation tool called heredoc that lets the
programmer create multi-line strings without using quotations. It begins with <<< and an
identifier (EOD- End of Document) is used both at the beginning and end of the string that can be
any combination of alphanumeric characters or underscores that don’t begin with a digit.
<?php
$abc = <<<EOD
This is a string created using heredoc syntax.
It can span multiple lines, use "quotes" without
escaping, and it'll allow $variables too.
Special characters are still supported \n as well.
EOD;
echo $abc
?>

d) Nowdoc Syntax Nowdoc syntax is functionally similar to quotes you encase in single
quoted strings, and you call it in much the same way that you call heredoc syntax. The
difference is that you enclose the identifier in single quotes when you open the string:
According to the PHP manual: Nowdocs are to single-quoted strings what heredocs are
to double-quoted strings.
For Example
<?php
$abc = <<<EOD
This is a string created using heredoc syntax.
It can span multiple lines, use "quotes" without
escaping, and it'll allow $variables too.
Special characters are still supported \n as well.;
echo $abc
?>

String Concatenation
It’s often necessary to join two strings together in a script. You accomplish this using the string
concatenation operator, a period (.). One can join two strings together by placing a period
between them while printing or creating a different vcariable:
<?php
$Place= "New York";
$Publisher= "MacGraw Hill";
$Year= "2007";
$imprint = "$Place"." : "."$Publisher".", "."$Year";

Print "$imprint";

?>

2. Integer
An integer is any positive or negative whole number (a number without a decimal value). For example, the
numbers 1, -27, and 4985067 are integers, but 1.2 is not. Because PHP is a loosely typed language, it’s not
necessary to declare a variable as an integer; however, if you find it necessary, you can explicitly cast, or
force, a value as an integer using the following syntax:
$foo = 27; // No quotes around a whole number always means integer
$bar = (int) "3-peat"; // Evaluates to 3

3. Float/ Decimal Point Numbers


Floating point numbers (also known as floats or doubles) are numbers with decimal values, or
real numbers. This includes numbers such as 3.14, 5.33333, and 1.1.

4. Boolean
A Boolean value is the simplest type of data; it represents truth, and can contain only one of two
values: TRUE or FALSE. It’s important to note that the FALSE (not in quotes) Boolean value is
different from the "FALSE" string value, and the same goes for TRUE. Boolean values are not
case sensitive. Booleans are very useful when determining if a condition exists.

5. Array
PHP arrays allow us to store groups of related data in one variable (as opposed to storing them in
separate variables). Arrays are among the most powerful datatypes available in PHP, due to their
ability to map information using a key to value pairing. This means that an array can store
multiple pieces of information in a single variable; all indexed by key. There are 3 different types
of PHP arrays:

i. Numeric arrays
ii. Associative arrays
iii. Multidimensional arrays

i. Numeric array
Numeric arrays use a number as the "key". The key is the unique identifier, or ID, of each item
within the array. The numbering starts at zero for each item of the array either automatically or
manually. Examples are given below:

Numeric array : automatic definition


Syntax Code
$arrayName = array(‘Value1’, ‘Value2’, <?php
‘Value3’); $fruit = array("Apples", "Strawberries",
"Blackberries");
echo $fruit[1];
?>

Numeric array : manual definition


Syntax Code
$arrayName[0] = "Value1"; <?php
$arrayName[1] = "Value2"; $fruit[0] = "Apples";
$arrayName[2] = "Value3"; $fruit[1] = "Strawberries";
$fruit[2] = "Blackberries";
echo $fruit[1];
?>

ii. Associative array


Associative arrays are similar to numeric arrays but, instead of using a number for the key, we use
a value followed by as assignment and value. Example of associated array is as follows:
Associative array
Syntax Code
$arrayName = array("keyName"=>"Value1", <?php
"keyName"=>"Value2", "keyName"=>"Value3"); $book= array(
'Author' => 'Silvershartz',
'Title' => 'Database Systems',
'Imprint' => 'Dhaka : DU, 2011',
'Call' => '064.5' );
print
$book["Author"]."<br/>".$book["Title"].".
".$book["Imprint"].". <br/>".$book["Call"];
?>

iii. Multidimensional arrays


Multidimensional arrays allow us to put an array inside another array. In other words, each of the
contents of the array is another array. The following diagram demonstrates this. We have an array
called "Food", which contains 3 arrays (called "Fruit", "Vegetables", "Grains"). Each of these
arrays contains their own arrays (one for each food within that group).

Example of Multi dimentional array Code


<?php
$Food = array
(
"Fruit"=>array
(
"Apples",
"Bananas",
"Oranges",
),
"Vegetables"=>array
(
"Carrots",
"Potatoes",
),
"Grains"=>array
(
"Oatbran",
)
);
echo “Best Food is ”. $Food[Vegetables][1].”.”
?>

Constants
Constants are like variables except that, once assigned a value, they cannot be changed. Constants are
created using the define() function and by convention (but not by rule) are in all uppercase letters.
Constants can be accessed from anywhere on the page.

Syntax and code for constant


Syntax Code
define('CONST_NAME',VALUE); <?php
define("name","Prince");
define("number","100");

print "my name is ".name."<br>";


print "my number is ".number;
?>

PHP Operator
Like other programming language PHP uses different operators to manipulate or perform operations on
variables and values. These are as follows:
i. Assignment Operators
ii. Arithmetic Operators
iii. Comparison Operators
iv. String Operators
v. Combination Arithmetic & Assignment Operators
vi. Logical Operators

i. Assignment operators
Assignment operators are used to set a variable equal to a value or set a variable to another variable's value.
Such an assignment of value is done with the "=", or equal character. Example:
$my_var = 4;
$another_var = $my_var;

ii. Arithmetic Operators


Operator Name Example
+ Addition <?php
- Subtraction $addition = 2+4;
* Multiplication $subtraction = 10-5;
/ Division $multiplication = 5*5;
% Modulus $division = 10/2;
$modulus = 43%10;
echo "addition: 2 + 4 = ".$addition."<br />";
echo "subtraction: 10 - 5 = ".$subtraction."<br />";
echo "multiplication: 5 *5 = ".$multiplication."<br />";
echo "division: 10 / 2 = ".$division."<br />";
echo "modulus: 43 % 10 = " . $modulus ;
?>

iii. Comparison Operators


Comparisons are used to check the relationship between variables and/or values. If you would like to see a
simple example of a comparison operator in action. Comparison operators are used inside conditional
statements and evaluate to either true or false. Here are the most important comparison operators of PHP.
Asume $x = 4 and $y = 5

Operator Name Example Result


== Equal To $x = = $y False
!= Not Equal To $x != $y True
< Less Than $x < $y True
> Greater Than $x > $y False
<= Less Than or Equal To $x <= $y True
>= Greater Than or Equal To $x >= $y False

iv. String operators


As we have already seen in the Arithmetic Operators Lesson, the period "." is used to add two strings
together, or more technically, the period is the concatenation operator for strings.
PHP Code:
Code Result
<?php Hello world !

$_a = “hello”;
$_b = “world”;
$_new = $_a . $_b;

print $_new . “!”;

?>

v. Combination Arithmetic & Assignment Operators


This combination assignment/arithmetic operator would accomplish the same task. The downside to this
combination operator is that it reduces code readability to those programmers who are not used to such an
operator. Here are some examples of other common shorthand operators. In general, "+=" and "-=" are the
most widely used combination operators.
Operator Name Example Equivalent operation
+= Plus Equals $x += 2 $x = $x + 2
-= Minus Equals $x -= 2 $x = $x – 2
*= Multiply Equals $x *=2 $x = $x * 2
/= Divide Equals $x /=2 $x = $x / 2
%= Modulo Equals Concatenate Equals $x %= 2 $x = $x % 2
.= $_a .= $b $_a = $_a . $_b

Logical Operators
The logical operators test combinations of booleans. The or operator, for example returns true if either the
left or the right operand is true.

Operator Name Return True If... Example Result


|| Or Left or right is true true || false True

&& And Left and right are true true && false False

! Not The single operand is not true ! true False

Increment and Decrement Variable


This may seem a bit absurd, but there is even a shorter shorthand for the common task of adding 1 or
subtracting 1 from a variable. To add one to a variable or "increment" use the
"++" operator:
$x++; Which is equivalent to $x += 1; or $x = $x + 1;

"--" operator:
To subtract 1 from a variable, or "decrement" use the "--" operator:
$x--; Which is equivalent to $x -= 1; or $x = $x - 1;

Control Structure
To add power and convenience to your scripts, PHP supports a number of conditional statements,
loops, and other control structures that allow us to manipulate data easily throughout your code.
The control structures supported by PHP are as follows and details are discussed later section:

Conditional Statements
1. if statement - use this statement to execute some code only if a specified condition is true
2. if...else statement - use this statement to execute some code if a condition is true and
another code if the condition is false
3. if...elseif....else statement - use this statement to select one of several blocks of code to
be executed
4. switch statement - use this statement to select one of many blocks of code to be executed

Looping
In PHP, we have the following looping statements and they have been discussed in the later
sections:
1. while - loops through a block of code while a specified condition is true
2. do...while - loops through a block of code once, and then repeats the loop as long as a
specified condition is true
3. for - loops through a block of code a specified number of times
4. foreach - loops through a block of code for each element in an array

Other keys used in controlling loops and functions


1. break - break ends execution of the current for, foreach, while, do-while or switch
structure.
2. continue - is used within looping structures to skip the rest of the current loop iteration
and continue execution at the condition evaluation and then the beginning of the next
iteration.
3. return- If called from within a function, the return() statement immediately ends
execution of the current function, and returns its argument as the value of the function
call.
4. require - it will halt the script whereas include() only emits a warning (E_WARNING)
which allows the script to continue.
5. include- The include() statement includes and evaluates the specified file.
6. require_once - is identical to require() except PHP will check if the file has already been
included, and if so, not include (require) it again.
7. include_once- The include_once() statement includes and evaluates the specified file
during the execution of the script.
8. goto- The goto operator can be used to jump to another section in the program.
i. The if Statement
The if statement evaluates an expression between parentheses. If this expression results in a true
value, a block of code is executed. Otherwise, the block is skipped entirely. This enables scripts to
make decisions based on any number of factors. The syntax of if statement is as follows:

If statement
Syntax Code and output
if ( expression ) <?Php
{ $number = 100;
code to execute if the expression evaluates to true if($number = = 100)
} {
print “Correct number”;
}
?>

output: Correct number

Here we use the comparison operator = = to compare the variable $number with the given number
100. If the assigned variable value and given number match, the expression evaluates to true, and
the code block below the if statement is executed. If you change the value of $number to "50"
and run the script, the expression in the if statement evaluates to false, and the code block is
skipped. The script remains sulkily silent. An alternative to the above if statement may be as
follows:

if ( $number == 100 )
print "Correct number";

ii. else
When working with if statement, we will often want to define an alternative block of code that
should be executed if the expression evaluates to false. We can do this by adding else to the if
statement followed by a further block of code:

else statement
Code Result
if ( expression ) <?Php
{ $number = 100;
code to execute if the expression evaluates to true if ($number == 100)
} {
else print “Correct number”;
{ }
code to execute in all other cases else
} {
print “Wrong number”;
}
?>
output: Wrong number

iii. elseif
we can use an if-elseif-else construct to test multiple expressions before offering a default block
of code: If the first expression does not evaluate to true, then the first block of code is ignored.
The elseif clause then causes another expression to be evaluated. Once again, if this expression
evaluates to true, then the second block of code is executed. Otherwise, the block of code
associated with the else clause is executed. we can include as many elseif clauses as you want,
and if you don't need a default action, you can omit the else clause.

elseif statement
Syntax Code and output
<?Php
if ( expression ) $number = 40;
{ if ($number == 50)
code to execute if the expression evaluates to {
true print 'Correct number';
} }
elseif ( another expression )
{ elseif ($number < 50)
code to execute if the previous expression {
failed and this one evaluates to true print 'It is less then your number';
else }
{
code to execute in all other cases elseif ($number > 50)
} {
print 'It is greater then your number';
}

else
{
print 'Wrong number';
}

?>
ElseIf is a Correct

Alternative syntax for control structures: (“:” operator)


i. PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and
switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and
the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. The following is an
if structure with elseif and else in the alternative format:

Syntax Code and output


<?php
if ( expression ) : if ($a == 5):
code to execute if the expression evaluates to echo "a equals 5";
true echo "...";
elseif ( another expression ) :
elseif ($a == 6):
code to execute if the previous expression echo "a equals 6";
failed and this one evaluates to true echo "!!!";
else : else:
code to execute in all other cases echo "a is neither 5 nor 6";
endif endif;
?>

Alternative syntax for control structures: (“?” operator)


The ? or ternary operator is similar to the if statement but returns a value derived from one of two
expressions separated by a colon. Which expression is used to generate the value returned
depends on the result of a test expression. If the test expression evaluates to true, the result of the
second expression is returned; otherwise, the value of the third expression is returned
Syntax Result
( expression ) ? <html>
returned_if_expression_is_true: <head><title>Example</title></head>
returned_if_expression_is_false; <body>
<?php
$_ct = “500”;
$_logic = (100 > $_ct)?”your number is correct” :
”your number is wrong”;
print $_logic;
?>
</body>
</html>

output: Your number is wrong

v. switch
If a multitude of conditions exist, you can use the switch control structure to create different
responses for different conditions—much as you can for an if statement. However, switch works
much better in situations where you have more than one or two conditions. A switch accepts an
expression, then sets up cases. Each case is functionally equivalent to an if statement; this means
that if the expression passed to the switch matches the case, then the code within the case is
executed. You must separate each case with a break statement

switch statement
Syntax Code and output
$Variable with value to check <?php
switch ($variable) $sub = "LIS";
{ echo " If your subject is $sub , ";
case1 ‘value to be evaluated’:
code; switch($sub)
break; {
. case 'sociology':
. echo "Your class number is: 301";
. break;
?> case 'Economics':
echo "Your class number is: 330";
break;
case 'LIS':
echo "Your class number is: 020";
break;
case 'CSE':
echo "Your class number is: 064";
break;
default:
echo "unknown subject";
break;
}
?>
output: If your subject is LIS , Your class
number is: 020

Looping
Loop statements are designed to enable you to achieve repetitive tasks. It decides how many
times to execute a block of code. Almost without exception, a loop continues to operate until a
condition is achieved, or you explicitly choose to exit the loop.

i. While Loop
The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as
long as the while expression evaluates to TRUE. The value of the expression is checked each time at the
beginning of the loop, so even if this value changes during the execution of the nested statement(s),
execution will not stop until the end of the iteration The syntax is for a while loop is:
Syntax Alternative syntax
while (expression) { while (expression) :
code to execute; } code to execute;
endwhile;

Example While Loop


Code Output
Example 1
<?php Number is 1
$num = 1; Number is 2
Number is 3
while ($num <= 10){ Number is 4
print "Number is $num<br />\n"; Number is 5
$num++; Number is 6
} Number is 7
Number is 8
print 'Done.'; Number is 9
?> Number is 10
Done
Example 2
<?php
Quantity Price
$brush_price = 5; 10 50
$counter = 10; 20 100
30 150
40 200
echo "<table border=\"1\" align=\"center\">"; 50 250
echo "<tr><th>Quantity</th>"; 60 300
echo "<th>Price</th></tr>"; 70 350
80 400
while ( $counter <= 100 ) { 90 450
echo "<tr><td>"; 100 500
echo $counter;
echo "</td><td>";
echo $brush_price * $counter;
echo "</td></tr>";
$counter = $counter + 10;
}
echo "</table>";
?>

ii. Do - While Loop


Do-while loops are very similar to while loops, except the truth expression is checked at the end
of each iteration instead of in the beginning. The main difference from regular while loops is that
the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at
the end of the iteration), whereas it may not necessarily run with a regular while loop. A "do
while" loop is a slightly modified version of the while loop. The do . . . while loop takes an
expression such as a while statement but places it at the end. The syntax is:

do {
code to execute;
} (expression);

While vs Do while loop


Do while while
<?php <?php
$i = 0; $i = 0;
do { while ($i > 0)
echo $i;
} while ($i > 0);
{
?> echo $i;
}
?>
Output: 0
Output: Nill

iii. For Loop


The for loop is simply a while loop with a bit more code added to it. The common tasks that are
covered by for loop are: a) Set a counter variable to some initial value; b) Check to see if the
conditional statement is true; C) Execute the code within the loop; d) Increment a counter at the
end of each iteration through the loop. The basic syntax is as follows:

for ( initialize a counter; conditional statement; increment a counter) { php code in the loop }

Note that Each step is separated by a semicolon: initialize counter, conditional statement, and the
counter increment. A semicolon is needed because these are separate expressions. However,
notice that a semicolon is not needed after the "increment counter" expression.
Example of for loop
<?php
/* example 1: Basic */

for ($i = 1; $i <= 10; $i++) {


echo $i;
}

/* example 2: Break statement 1 */

for ($i = 1; ; $i++) {


if ($i > 10) {
break;
}
echo $i;
}

/* example 3: Break statement 2 */

$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);


?>

iv. For each Loop

This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue
an error when you try to use it on a variable with a different data type or an uninitialized variable.
There are two syntaxes; the second is a minor but useful extension of the first.

i. as $value: On each loop, the value of the current element is assigned to


$value and the internal array pointer is advanced by one. When foreach first
starts executing, the internal array pointer is automatically reset to the first
element of the array. This means that you do not need to call reset() before a
foreach loop.

ii. as $key => $value): does the same thing, except that the current element's
key will be assigned to the variable $key on each loop. The operator "=>"
represents the relationship between a key and value.

Foreach loop syntax and example


Syntax 1 Example
foreach (array_expression as $value) <?php
statement $x=array("one","two","three");
foreach ($x as $value) {
echo $value . "<br />"; }
?>

Syntax 2 Example
foreach (array_expression as $key => <?php
$value) $x=array(0=>"one",1=>"two",2=>"three");
statement foreach ($x as $key=>$value) {
echo "key = " .$key ." value = ".$value. "<br />"; }
?>

PHP Function
What is function? You can think of a function as a machine. A machine takes the raw
materials you feed it and works with them to achieve a purpose or to produce a product. A
function accepts values from you, processes them, and then performs an action (printing to the
browser, for example) or returns a new value, possibly both. A function, then, is a self-contained
block of code that can be called by your scripts. When called, the function's code is executed. You
can pass values to functions, which they will then work with. When finished, a function can pass
a value back to the calling code.

i. Calling a Function
Functions come in two flavors— those built in to the language and those you define yourself.
PHP4 has hundreds of built-in functions. The very first script in this tutorial consisted of a single
function call. For example, print("Hello Web"). We called the print() function, passing it the
string "Hello Web". The function then went about the business of writing the string. A function
call consists of the function name, print in this case, followed by parentheses. If you want to pass
information to the function, you place it between these parentheses. A piece of information
passed to a function in this way is called an argument. Some functions require that more than one
argument be passed to them. Arguments in these cases must be separated by commas: for
example: some_function( $an_argument, $another_argument ); The abs() function, for example, requires
a signed numeric value and returns the absolute value of that number.
Function calling: Abs function
Code Result
<?php 1200
$_number = -1200;
$new_number = abs($_number);
print $new_number;
?>

ii. Creating a Function


A function may be defined using syntax such as the following. Function names follow the same
rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores. Also note that a function name should reflects
what the function does.

Creating a simple function


Syntax Code with Result
function functionName() <?php
{ function myname() {
//code to be executed; echo “Prince”; }
} echo “my name is ”;
myname();
?>

Output: My name is prince

iii. Adding parameters


To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.

Creating functions with parameter


Code Result
<?php my name is prince
function myname($_name) { my friend name is john
echo $_name; }

echo "my name is ";


myname("prince ");
echo "<br>my friend name is ";
myname("john ");
?>

iv. Returning values


Values are returned by using the optional return statement. Any type may be returned, including arrays and
objects.

Use of return in function


Code Result
<?php The total mark is 75
function tm($a,$b) {
$total = $a + $b;
return $total; }

echo "The total mark is ";


tm(50,25);
?>

v. Dynamic Function Calls


It is possible to assign function names as strings to variables and then treat these variables exactly as you
would the function name itself.

PHP Code:
Code Result
<?php The total mark is 75
function tm($a,$b) {
$total = $a + $b;
return $total; }

$totalmarks = “tm”;

echo "The total mark is ";


$totalmarks(50,25);
?>

vi. Accessing Variables with the global Statement


From within a function, it is not possible by default to access a variable that has been defined elsewhere. If
you attempt to use a variable of the same name, you will set or access a local variable only. The following
script will output 3. By declaring $a and $b global within the function, allreferences to either variable will
refer to the global version. There is no limit to the umber of global variables that can be manipulated by a
function.

Accessing global Variables


Code Result
<?php 3
$a = 1;
$b = 2;
function Sum() {
global $a, $b;
$b = $a + $b; }
Sum();
echo $b;
?>

You might also like