PHP Arrays
> An array variable is a storage area holding a
number or text. The problem is, a variable will hold
only one value.
> An array is a special variable, which can store
multiple values in one single variable.
PHP Arrays
If you have a list of items (a list of car names, for
example), storing the cars in single variables
could look like this:
PHP Arrays
> However, what if you want to loop through the
cars and find a specific one? And what if you had
not 3 cars, but 300?
> The best solution here is to use an array.
> An array can hold all your variable values under
a single name. And you can access the values by
referring to the array name.
> Each element in the array has its own index so
that it can be easily accessed.
PHP Arrays
In PHP, there are three kind of arrays:
> Numeric array - An array with a numeric index
> Associative array - An array where each ID
key is associated with a value
> Multidimensional array - An array containing
one or more arrays
PHP Numeric Arrays
> A numeric array stores each array element with
a numeric index.
> There are two methods to create a numeric
array.
PHP Numeric Arrays
In the following example the index is automatically
assigned (the index starts at 0):
In the following example we assign the index
manually:
PHP Numeric Arrays
In the following example you access the variable
values by referring to the array name and index:
The code above will output:
PHP Associative Arrays
> With an associative array, each ID key is
associated with a value.
> When storing data about specific named values,
a numerical array is not always the best way to do
it.
> With associative arrays we can use the values
as keys and assign values to them.
PHP Associative Arrays
In this example we use an array to assign ages to
the different persons:
This example is the same as the one above, but
shows a different way of creating the array:
PHP Associative Arrays
PHP Multidimensional Arrays
In a multidimensional array, each element in the
main array can also be an array.
And each element in the sub-array can be an
array, and so on.
PHP Multidimensional Arrays
PHP Multidimensional Arrays
PHP Multidimensional Arrays
PHP - Sort Functions For Arrays
we will go through the following PHP array sort functions:
● sort() - sort arrays in ascending order
● rsort() - sort arrays in descending order
● asort() - sort associative arrays in ascending order, according
to the value
● ksort() - sort associative arrays in ascending order, according
to the key
● arsort() - sort associative arrays in descending order, according
to the value
● krsort() - sort associative arrays in descending order, according
to the key
Sort functions
<?php <?php
$age = array("Peter"=>"35", "Ben"=>"43",
"Joe"=>"41");
$numbers = array(4, 6, 2, 22, 11);
krsort($age); rsort($numbers);
//a=>sort ascending =>value //2 4 6 11 22
//k=>sort ascending =>key
//ar=>sort descending =>value
$arrlength = count($numbers);//5
//kr=>sort descending =>key
for($x = 0; $x < $arrlength; $x++) {
foreach($age as $x => $x_value) {
echo $numbers[$x];
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
echo "<br>";
} }
?> ?>
PHP Loops
> Often when you write code, you want the same
block of code to run over and over again in a row.
Instead of adding several almost equal lines in a
script we can use loops to perform a task like this.
> In PHP, we have the following looping
statements:
PHP Loops
> while - loops through a block of code while a
specified condition is true
> do...while - loops through a block of code once,
and then repeats the loop as long as a specified
condition is true
> for - loops through a block of code a specified
number of times
> foreach - loops through a block of code for each
element in an array
PHP Loops - While
The while loop executes a block of code while a
condition is true. The example below defines a
loop that starts with
i=1. The loop will
continue to run as
long as i is less
than, or equal to 5.
i will increase by 1
each time the loop
runs:
PHP Loops - While
PHP Loops – Do ... While
The do...while statement will always execute the
block of code once, it will then check the
condition, and repeat the loop while the condition
is true.
The next example defines a loop that starts with
i=1. It will then increment i with 1, and write some
output. Then the condition is checked, and the
loop will continue to run as long as i is less than,
or equal to 5:
PHP Loops – Do ... While
PHP Loops – Do ... While
PHP Loops - For
PHP Loops - For
Parameters:
> init: Mostly used to set a counter (but can be
any code to be executed once at the beginning
of the loop)
> condition: Evaluated for each loop iteration. If
it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
> increment: Mostly used to increment a counter
(but can be any code to be executed at the end
of the loop)
PHP Loops - For
The example below defines a loop that starts with
i=1. The loop will continue to run as long as i is
less than, or equal to 5. i will increase by 1 each
time the loop runs:
PHP Loops - For
PHP Loops - Foreach
For every loop iteration, the value of the current
array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop
iteration, you'll be looking at the next array value.
PHP Loops - Foreach
The following example demonstrates a loop that
will print the values of the given array:
PHP Loops - Foreach
Winner of the most impressive slide award
PHP Break
It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
PHP exit() function
It is an inbuilt function which is used to output a message and terminate the
current script.
The exit() function only terminates the execution of the script.
The message to be displayed is passed as a parameter to the exit() function
and it terminates the script and displays the message.
The exit() function is an alias of the die() function
<?php
$link = "https://www.geek1234.org";
// opening a link
fopen($link, "r")
//using exit() to display message and terminate script
or exit("Unable to establish a connection to $link");
?>
<?php <?php
for ($x = 0; $x < 10; $x++) {
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
if ($x == 4) {
continue;
break;
}
} echo "The number is: $x <br>";
echo "The number is: $x }
<br>";
?>
} Output:
?> The number is: 0
The number is: 1
Output: The number is: 2
The number is: 0 The number is: 3
The number is: 5
The number is: 1 The number is: 6
The number is: 2 The number is: 7
The number is: 3 The number is: 8
The number is: 9
PHP Functions
> We will now explore how to create your own
functions.
> To keep the script from being executed when
the page loads, you can put it into a function.
> A function will be executed by a call to the
function.
> You may call a function from anywhere within a
page.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly,
from within a script, to perform a specific task.
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your
own functions.
A function is a block of statements that can be used repeatedly in
a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
PHP Functions
A function will be executed by a call to the
function.
> Give the function a name that reflects what the
function does
> The function name can start with a letter or
underscore (not a number)
PHP Functions
A simple function that writes a name when it is
called:
PHP Functions - Parameters
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.
PHP Functions - Parameters
PHP Functions - Parameters
PHP Functions - Parameters
This example adds
different punctuation.
PHP Functions - Parameters
Callback Functions
A callback function (often referred to as just
"callback") is a function which is passed as an
argument into another function.
Any existing function can be used as a callback
function. To use a function as a callback
function, pass a string containing the name of
the function as the argument of another
function:
<?php
function my_callback($item) { Output:
return strlen($item); Array ( [0] => 5 [1] => 6
} [2] => 6 [3] => 7 )
$strings = ["apple", "orange",
"banana", "coconut"];
$lengths =
array_map("my_callback",
$strings);
print_r($lengths);
?>
String Manipulation Functions
1) strlen()
2) explode()
3) implode()
4) strpos()
5) str_repeat
6) strrev()
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
▪ strlen() function returns the length of a string.
▪ str_word_count() function counts the number of words in a
string.
▪ strrev() function reverses a string.
▪ strpos() function searches for a specific text within a string. If a
match is found, the function returns the character position of
the first match. If no match is found, it will return FALSE.
▪ str_replace() function replaces some characters with some
other characters in a string.
▪ implode() function returns a string from the elements of an
array.
▪ explode() function breaks a string into an array
<?php
echo strlen("Hello world!");
echo "<br>";
echo str_word_count("Hello world!");
echo "<br>";
echo strrev("Hello world!");
echo "<br>";
echo strpos("Hello world!", "world");
echo "<br>";
echo str_replace("world", "Dolly", "Hello world!");
echo "<br>";
echo str_repeat("Wow",13);
Date & Time Functions
1) date() function formats a timestamp to a more
readable date and time.
2) checkdate()
3) mktime()
PHP Forms - $_GET Function
> The built-in $_GET function is used to collect
values from a form sent with method="get".
> Information sent from a form with the GET
method is visible to everyone (it will be displayed
in the browser's address bar) and has limits on the
amount of information to send (max. 100
characters).
PHP Forms - $_GET Function
Notice how the URL carries the information after the file name.
PHP Forms - $_GET Function
The "welcome.php" file can now use the $_GET
function to collect form data (the names of the
form fields will automatically be the keys in the
$_GET array)
PHP Forms - $_GET Function
> When using method="get" in HTML forms, all
variable names and values are displayed in the URL.
> This method should not be used when sending
passwords or other sensitive information!
> However, because the variables are displayed in
the URL, it is possible to bookmark the page. This
can be useful in some cases.
> The get method is not suitable for large variable
values; the value cannot exceed 100 chars.
PHP Forms - $_POST Function
> The built-in $_POST function is used to collect
values from a form sent with method="post".
> Information sent from a form with the POST
method is invisible to others and has no limits on
the amount of information to send.
> Note: However, there is an 8 Mb max size for
the POST method, by default (can be changed by
setting the post_max_size in the php.ini file).
PHP Forms - $_POST Function
And here is what the code of action.php might look like:
PHP Forms - $_POST Function
Apart from htmlspecialchars() and (int), it should
be obvious what this does. htmlspecialchars()
makes sure any characters that are special in html
are properly encoded so people can't inject HTML
tags or Javascript into your page.
For the age field, since we know it is a number,
we can just convert it to an integer which will
automatically get rid of any stray characters. The
$_POST['name'] and $_POST['age'] variables
are automatically set for you by PHP.
PHP Forms - $_POST Function
When to use method="post"?
> Information sent from a form with the POST
method is invisible to others and has no limits
on the amount of information to send.
> However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.