Main Page

Introduction

Hi!
This site is created mostly for myself, creating an overview of the basics of PHP.
To distinguish between different kinds of text i will use colors:
I will use blue for important facts and syntax.
I will use orange for code.
I will use purple to show how the result of the executed code.

Contents


Array ( [urlid] => main.php )
- if statements
- else and elseif
- Logical operators
- Switch statements
- While loops
- For loops
- foreach loops
- Continue
- Array pointers
- Functions: Define Function
- Functions: Arguments
- Functions: Returning Values
- Functions: Returning Multiple Values
- Scope and Global Variables
- Functions: Default Argument Vaules
- Webpages: Links and URLs
- Webpages: Links and URLs - Get

if statements

IF statements are built on the following syntax:

if (Expression) {
execute this part;
}

Here is an example :

<?php
//value is larger than value
$a = 2;
$b = 1;

//Performing the IF:
if ($a > $b) {
echo "a is larger than b";
}
?>

This is what it looks like when the code is executed:

a is larger than b

Another example. Here it is about welcoming new users if the $new_user value is valid:

<?php
//only welcome new users
$new_user = true;
if ($new_user) {
echo "Welcome!<br>";
echo "We are glad you decided to join us!";
}
?>

Here is what it looks like when the code is executed:

Welcome!
We are glad you decided to join us!

else and elseif

Else and Elseif statements are built on the following syntax:

if (expression) {
Execute this due to this expression
} elseif (expression) {
Execute this due to this expression
} else {
execute this due to no spesified expression
}

Here is an example of a value comparison between the value $a and the value $b.
We are going to detect which value is the greatest, or if they are equal:

// Detect largest value using else and elseif
if ($a > $b){
echo "a is larger than b";
}elseif ($a < $b) {
echo "a is smaller than b";
}else{
echo "a is equal to b";
}

It will look like this when executed:

a is larger than b

Logical operators

Comparison operators: Equal - Not equal

Here are some comparison operators using the = sign:

Set a value: =
Equal: ==
Identical: ===

The differense between equal and identical is that 1 2 3 as numbers can be equal to "1" "2" "3" as string values.
When using identical it has to be the exact same! which means that the number 2 is not identical to the string "2"

Here are some comparison operators using the NOT equal:

Not equal: !=
Not identical: !==

Notice that one of the equal [=] signs are replaced by the exclamation point [!] when using NOT equal or identical

Logical operators [ AND -- OR -- NOT]

and: &&

AND require to include combination as a neccesity. If a value meets a certain requirement AND the other value meets a certain requirement, THEN we can execute the following code


or: ||

OR require only to meet one of the chosen requirements. If a value meets a certain requirement OR the other value meets a certain requirement, THEN we can execute the following code


not: !

NOT require a valute to not meet a certain requirement. If a value does not meet a certain requirement, THEN we can execute the following code

Here is an example using AND in a IF-else:

<?php
//value comparison sample using AND,meaning both conditions needs to be met
$a = 4;
$b = 3;
$c = 1;
$d = 20;

if ( ($a > $b) && ($c > $d) ){
echo "a is larger than b AND ";
echo "c is larger than d";
} else {
echo "negative";
}
?>

This is how the code looks like when executed:

negative

Since c is not larger than d, it will display the negative text. Lets do the same using OR instead:

<?php
//value comparison sample using OR, only one of the two conditions need to be met
$a = 4;
$b = 3;
$c = 1;
$d = 20;

if ( ($a > $b) || ($c > $d) ){
echo "a is larger than b AND ";
echo "c is larger than d";
} else {
echo "negative";
}
?>

Here is what the code looks like when it is executed:

a is larger than b AND c is larger than d

Now it will display that a is larger than b, and that c is larger than d. Allthough c is not larger than d, but because of the fact that one of the two conditions are met it will now display this

Using the empty operator

You do not want to accept blank / NULL values but you do want to accept 0 or 0.0. What you can do is use the logical && operator and make sure the value entered is not empty as in NULL or not numeric:

<?php
// dont reject 0 or 0.0
$quantity = "";

if ( empty($quantity) && !is_numeric($quantity) ){
echo "you must enter a quantity.";
} else {
echo "you have entered a quantity";
}
?>

The code will look like this when executed:

you must enter a quantity.

Switch statements

Switch statements are built using the following syntax:

switch (Value){
case if_this_is_within_chosen_value:
execute this
case if_this_is_within_chosen_value:
execute this
default:
execute this if none of the desired values where correct
}

Here is an example of a case where we have a value named $number and what happends depending on different set values:

<?php
// Switch with break
$number = 3;

switch ($number){
case 0:
echo "number equals zero";
break;
case 1:
echo "number equals one";
break;
case 2:
echo "number equals two";
break;
case 3:
echo "number equals three";
break;
default:
echo "number equals none of the options";
break;
}
?>

Here is what the code looks like when executed:

number equals three

Switch with multiple values

Sometimes it is necessary to execute one statement for several cases. here is an example of how to do this in php:

<?php // use case with one statement for multiple cases

//define usertype:
$user_type = "customer";

switch ($user_type){ //Begin:

//Single case
case "student":
echo "welcome youngling";
break;

//Double case
case "press";
case "customer";
echo "Hello you whom i want to give a great impression";
break;

// triple case
case "board_members";
case "boss" ;
case "officials";
echo "We are making alot of money";
break;

//Add as many cases you want by stacking them, then execute a command
} //End of switch

?>

Here is how the code looks when executed:

Hello you whom i want to give a great impression

As you can see, the execution of one of the commands can occur to multiple case values such as student, baby, teenager etc..

While loops

The while-loop syntax looks like :

While (expression) {
this gets executed;
}

A While-loop does the execution part while the expression still is valid, and will loop untill it is not

Here is an example:

<?php // a while-loop

//define a value
$count = 0;

//do something while that value meets a condition:
while ( $count <= 10 ) {
echo $count . ", ";

//increment value to avoid ethernal-loop
$count += 1;
//could do $count++;
}

?>

The code will look like this when executed:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

An example with the modulo operator:

<?php
// an example of a while loop using increments
//and modulo operator to separate odds from evens
$counter = 0;
while ( $counter <= 20 ) {

// what is left after dividing by 2?
if ( ($counter % 2) == 0 ) {
echo $counter . " er partall <br>\n";
} else {
echo $counter . " er oddetall <br>\n";
}

//Increment to avoid ethernal loop
$counter += 1;
}

echo "ferdig";
?>

When executed the code will look like this:

0 er partall
1 er oddetall
2 er partall
3 er oddetall
4 er partall
5 er oddetall
6 er partall
7 er oddetall
8 er partall
9 er oddetall
10 er partall
11 er oddetall
12 er partall
13 er oddetall
14 er partall
15 er oddetall
16 er partall
17 er oddetall
18 er partall
19 er oddetall
20 er partall
ferdig

For loops

The syntac for a for loop would look like this :

for (initial; do_untill_conditions_met; todo_each_time) {
execute this;
}

Here is an example on how to use a for-loop:

<?php

// simple for loop for incrementing numbers
for( $count = 0; $count <= 10; $count+=1){
echo $count . ", ";
}

?>

This is what the code looks like when executed:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Another example:

<?php

// example with odds and evens
for ($count = 20; $count > 0; $count-=1){
if ( ($count % 2) == 0) {
echo "{$count} is even.<br />\n";
}else {
echo "{$count} is odd.<br />\n"; }
}

?>

When the code is executed it will look like this:

20 is even.
19 is odd.
18 is even.
17 is odd.
16 is even.
15 is odd.
14 is even.
13 is odd.
12 is even.
11 is odd.
10 is even.
9 is odd.
8 is even.
7 is odd.
6 is even.
5 is odd.
4 is even.
3 is odd.
2 is even.
1 is odd.

foreach loops

The syntax of a foreach loop looks like this:

foreach ( $array as $value ) {
execute this;
}

Here is an example of a foreach loop that echoes all the values of an array back to the webbrowser:

<?php //example of a foreach loop that echoes all the values back:

//Defining an array with values:
$ages = array(4,8,15,16,23,42);

//looping it:
foreach ($ages as $value){
echo "Age: {$value}<br>\n";
}

?>

This is what the code looks like when executed:

Age: 4
Age: 8
Age: 15
Age: 16
Age: 23
Age: 42

Here is a more complex example of a foreach loop using assoc. array, where each attribute of a person is listed with the value:

<?php // foreach using assoc. array

//Defining an array
$person = array(
"first_name" => "Alexander",
"last_name" => "Klein",
"address" => "Ringvålvegen 352b",
"city" => "Trondheim",
"state" => "Sør Trønderlag",
"zip_code" => "7038"
);

echo "<table border=2>";

//Executing the foreach within a table:
foreach ($person as $attributt => $verdi){
echo "<tr>";
$fix_attr = ucwords(str_replace("_", " ", $attributt));
echo "<td>{$fix_attr}</td> <td>{$verdi}</td>";
echo "</tr>";
}

echo "</table>";

?>

The code will look like this when executed:

First Name Alexander
Last Name Klein
Address Ringvålvegen 352b
City Trondheim
State Sør Trønderlag
Zip Code 7038

Yet another example:

<?php
$prices = array("Brand new computer" => 2000,
"1 month of lynda.com" => 25,
"learning PHP" => null
);
foreach ($prices as $item => $price){
echo "$item; ";
if (is_int($price)){
echo $price . "$";
} else {
echo "priceless";
} //end of if
echo "<br>";
} // end of foreach

?>

Executing the code will look like this:

Brand new computer; 2000$
1 month of lynda.com; 25$
learning PHP; priceless

Continue

Continue will immediately continue the loop, incrementing the value and moving on, without executing any more of the code within the loop. To understand what a continue does, imagine that there is a continue at the end of every for-loop. By manually placing it within a for-loop, you hasten the "end-game" and it will be as if you just skipped the code within the for loop for that exact value.

Here is an example of how to use a contiune:

<?php
/* this for loop sets 0 as start value,
will loop as long as value is less than or equal to 10,
and it will increment by 1 */

for ($count=0; $count <= 10; $count+=1) {

if ($count == 5){
// we placed continue here. It skips the rest and increments the count
continue;
} //If is done

echo $count . ", ";

// this is where it would normally execute the continue; and set $count += 1,
// as we have reached the end of the for-loop
} // for is done

?>

Array pointers

Array pointers can be used to navigate trough the values within the arrays. It is possible to show current, goto next, goto previous, goto end, goto beginning

How to use Array pointers

Here are som ways of using Array pointers to navigate an array:

current($array) - Shows what value is pointed out/selected in the array.
next($array) - Moves the poinger to the next value in the array, like placing a continue within a loop.
prev($array) - Moves the pointer to the previous value in the array.
end($array) - moves the pointer to the end of the array.
reset($array) - Moves the pointer to the beginning of an array

Here is an example to show how to use array pointers:

<?php // show the currently selected value within an array
//define an array
$ages = array(4,8,15,16,23,42);

//list all the ages with a position
$array_counter = 0;
foreach ($ages as $value){
$array_counter += 1;
echo "[" . $array_counter . "]" . $value . " ";
}
echo "<br>";

// reset the array
reset($ages);
// show current value
echo "current: " . current($ages) . "<br>";
//Next value: move the pointer forward(like continue inside a loop)
next($ages);
echo "pointer_1_next: " . current($ages) . "<br>";
//Skip 2 values
next($ages);
next($ages);
echo "2 more skips: " . current($ages) . "<br>";
// one backwards
prev($ages);
echo "go 1 back: " . current($ages) . "<br>";
// all the way do the end.
end($ages);
echo "goto_end: " . current($ages) . "<br>";
//reset the array
reset($ages);
echo "back to beginning : " . current($ages) . "<br>";
?>

This is how the code looks when executed:

[1]4 [2]8 [3]15 [4]16 [5]23 [6]42
current: 4
pointer_1_next: 8
2 more skips: 16
go 1 back: 15
goto_end: 42
back to beginning : 4

Functions: Define Function

A function is a block of statements that can be used repeadetly in a program
It will not execute immediately, but has to be called upon.

The syntax of a function would look like this:

function nameoffunction($parameter1, $parameter2, $parameter3){
code to be executed and often calls upon the parameters;
}

Her is an example of a function:

<?php
// Simple echo function
Function say_hello(){
echo "Hello World!<br>";
}
say_hello();
// echo with parameter function
function say_hello_to ($word) {
echo "Hello $word !<br>";
}
say_hello_to(alexander);
say_hello_to(Everyone);
?>

Here is what it looks like when executed:

Hello World!
Hello alexander !
Hello Everyone !

Remember:

-A function can not be redefined
-A function can be defined after it is being called upon since php will go trough the code before it starts to handle it.

Functions: Arguments

Arguments

Arguments are values that a function recieves from the outside environemnt.
The defined function will work with this arguments and return a result.
The name of an oustide variable does not have tomatch the name of the argument.
Here is an example of a function using arguments:

<?php
//first we define a name:
$defined_name="John Doe";
//here is a function with 3 arguments. Notice the names used:
function better_hello($greeting, $target, $punct) {
//echo out the information:
echo $greeting . " " . $target . $punct . "<br>";
}
// here we call upon the function in differend ways:
better_hello("Normal greeting: Hello", $defined_name, "!");
better_hello("Stronger punct: Hello", $defined_name, "!!!");
better_hello("Punct defined as null: Hello", $defined_name, null)
?>

Here is what it looks like when executed:

Normal greeting: Hello John Doe!
Stronger punct: Hello John Doe!!!
Punct defined as null: Hello John Doe

Functions: Returning Values

A function can return values using the return command
return exits the function and sends the return value as a result
It works like the break command does in a switch statement.

Here is how the syntax of a function returning values looks like:

function Name_Of_Function($argument_A, $argument_2){
$Putting_them_together = $argument_A + $argument_2;
return $Putting_them_together;
}

Using a function:
echo namedFunction1(2,3)

Here is an exapmple of using returning values within a function:

<?php
//example of returning value
function add($val1, $val2) {
$sum = $val1 + $val2;
// Returning a value will make it flexible to work with
return $sum;
}

//Use the function to create results:
$result1 = add(3,4);
// Use a existing result in a new result:
$result2 = add(5, $result1);
//project the result in the browser:
echo $result2;

?>

When executed the code will look like this:

12
It is recommended to leave echo out of a function

Here is an example of the Chinese Zodiac as a function:

<?php // Chinese Zodiac as a function

function chinese_zodiac($year) {

//Do what a zodiac calendar does
$conv_value = (($year - 4) % 12);

switch ($conv_value){
case 0: return "Rat";
case 1: return "Ox";
case 2: return "Tiger";
case 3: return "Rabbit";
case 4: return "Dragon";
case 5: return "Snake";
case 6: return "Horse";
case 7: return "Goat";
case 8: return "Monkey";
case 9: return "Rooster";
case 10: return "Dog";
case 11: return "Pig";
}
} //end of function
// Getting some results:
$zodiac = chinese_zodiac(2013);
echo "2013 is the year of the : " . $zodiac . "<br>";
echo "2027 is the year of the : " . chinese_zodiac(2027) . "<br>";
?>

Here is what the code looks like when executed:

2013 is the year of the : Snake
2027 is the year of the : Goat

Functions: Returning Multiple Values

Return can not handle more than one value. If you want to return more than one value you have to return an array with all the desired values.

Here is an example of how to return multiple values using an array:

<?php //multiple values
function add_subt($val1, $val2){
$add = $val1 + $val2;
$subt = $val1 - $val2;

//Returning both in an array
//let us bring out multiple values
return array($add, $subt);
}

// ###the simple way
//result_array is now recieving an array:
$result_array = add_subt(10,5);

//echo out both array_values:
echo "add: " . $result_array[0] . "<br>";
echo "subtract: " . $result_array[1] . "<br>";


// ### with list
list($add_result, $subt_result) = add_subt(20,7);

//echo out both array_values:
echo "add: " . $add_result . "<br>";
echo "subtract: " . $subt_result . "<br>";

?>

Here is the result of executing that code:

add: 15
subtract: 5
add: 27
subtract: 13

Scope and Global Variables

Having a variable on the inside of a function not being accessible on the outside of the function by default is due to a variable scope.
The function is then the variable's scope. There's two main scopes:
-Global scope
-Local scope(restricted reachability due to isolation)
A variable inside of a function can be defined as global by using "global $variable_name"

Here is an example of using local and global variables:

<?php
$bar = "outside"; // global scope

function foo(){

// ## edit: adding in the variable declared as a global variable
//defining $bar as global. Getting it from outside
global $bar;

// ## edit: adding in this if, to check if $bar exists
if (isset($bar)){
echo "foo: " . $bar . "<br>";
} // End of if

$bar = "inside"; //local scope
}

//echoing out variable $bar. Now it is the global one we are calling
echo "1: " . $bar . "<br>";

//calling the function foo() .... but not echoing out.
// ## edit echoing when defining $bar as global
foo();

//echoing out $bar again. still it is the global one we are calling
// ## edit: echoing out the inside variable as it is now declared global and redefined inside function
echo "2:" . $bar . "<br>";
?>

This is what the code looks like when executed

1: outside
foo: outside
2:inside

Functions: Default Argument Vaules

Normally a function with 2 arguments must be called with 2 values for matching those arguments. There is a way around that, by setting default argument values

Here is an example containing a function as it evolves over 3 versions. It evolves so that it can be called upon without any arguments:

<?php // foreach using assoc. array
<?php
// Ver 1
function paint_v1($color){ //requires a value for $color
return "Ver:1 - The color of the room is " . $color . "<br>";
}

//will result in error due to lack of value
// echo paint_v1();

//will work due to provided value:
echo paint_v1("blue");

// Ver 2
function paint_v2($color="red_default"){ // now has a default argument value
return "Ver:2 - The color of the room is " . $color . "<br>";
}

//can now be called upon without a value
echo paint_v2();

// Ver 3
function paint_v3($room="office_default",$color="red_default"){
return "The color of the " . $room . " is " . $color . ".<br>";
}

//can now be called upon wihtout any values
echo paint_v3();
echo paint_v3("bedroom","blue");
echo paint_v3("bedroom",null);

//important to have important arguments first, then have optionals afterwards.
?>

When executed the code will look like this:

Ver:1 - The color of the room is blue
Ver:2 - The color of the room is red_default
The color of the office_default is red_default.
The color of the bedroom is blue.
The color of the bedroom is .

Webpages: Links and URLs

Lets look at the Request Response Cycle:

[Start]| enduser@browser request -- Going to webserver[proccesses php, creating a html page] -- returns html to enduser@browser [End]

The request will always come from the enduser@browser. Initial request will not come from the webserver.
There are 3 ways we can recieve data requests from endusers on the web:

URLs and Links are GET requests
Forms are POST request
Cookies -- the way we access COOKIE information that piggy backs on each request

Example of how to use php with links


first_page.php
//simulates a page that contains a link

Examplecode:

<?php
//First we create som values that we will use within the link
$url = "second_page.php";
$link_name = "Link to second Page";
$id = 2;

//now we can use these variables within the html url
echo <a href="$url?id=$id">$link_name</a>


?>

This is how the code looks like when executed:

Link to second Page

second_page.php
//simulates a webpage that first_page.php linked to

Value recieved from first_page.php is: 2

Webpages: Links and URLs - Get

The syntax of using Get requests looks like this:

somepage.php?named_variable="valueofvariable"
somepage.php?named_variable="valueofvariable"&another_var="valueofvar2"
questionmark - variablename = recieved_value & variablename2 = recieved_value2

Super global variable:
-Always available in all scopes
-Assigned by PHP before processing page code
$_GET - superglobal where query parameters are set by php

$_ - All superglobals start with this two symbols

www.cloudberry.it