электронная
432
печатная A5
645
6+
PHP Programming for Beginners

Бесплатный фрагмент - PHP Programming for Beginners

Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO)


5
Объем:
242 стр.
Возрастное ограничение:
6+
ISBN:
978-5-4490-9015-7
электронная
от 432
печатная A5
от 645

Introduction

DISCLAIMER

The information presented in this eBook is sold without warranty either expressed or implied. The author will hold no liability for any damages caused either directly or indirectly by the instructions contained in this book, or by the software products recommended for installation and usage.

Who Should Read This Book?

Those who wish to learn computer programming in PHP should be familiar with HTML, as a knowledge of HTML will be helpful in your efforts. This book is also for those who know other programming languages and wish to learn PHP as well.

PHP is a server-side scripting language executed on a web server, sending HTML pages to the browser. Included in the following are instructions for the installation of Apache Web Server, PHP, MySQL database, and phpMyAdmin script used for MySQL database administration. And please note that all of the above-mentioned software can be readily obtained and used free of charge.

Programming in any computer language or script is not as impossible as one might think.

Perhaps you’re thinking that being very good at math is a prerequisite to becoming a computer programmer, however, this is not necessarily so. The average person can master computer programming. In fact, a study revealed that, among immigrants, former musicians tended to make good programmers, probably because writing music is much like writing code.

In a sense, programming is like packaging something because programming language deals with variables that are used to hold different pieces of data. What is a variable? Think of a variable as you would a box for packaging. When you select a box, you must consider the size and nature of the item (s) being packaged.

Numbers, text strings, and objects are what comprise a computer program. A variable might contain whole numbers, fractions, or pieces or strings of text. A variable that contains a whole number is called an integer. A variable holding a number with a decimal point is called a float or double, while a variable holding a piece of text is called a string.

Computer programs begin with a variable declaration and, with some exceptions, the data type. For example, in C++ or Java, you must declare the variable name and exact data type. A variable name, in any computer language, must be only one word. It may contain alphabetical characters, numbers, and underscores. Often programmers use prefixes to show variable data types. For example, strName for a string data type or int_Account for an integer data type, and so on.

The integer, double, string, and date are all data types. Each data type requires a different “space” in the computer memory. For example, an integer occupies four bytes, or, because there are 8 bits to a byte, 32 bits — a bit being the smallest unit of information. A bit may contain a 0 or a 1. In the binary system 00000001 equals 1, 00000010 equals 2, 11111111 equals 256, or 2 to the 8th power.

Four bytes can hold numbers from -2,147,483,648 to +2,147,483,647.

A Double occupies 8 bytes. Huge numbers with decimals can be held in a double. A float occupies 4 bytes and can hold a number with decimals. When selecting a gift box for a diamond ring, you wouldn’t choose a yard-by-yard box because it wouldn’t be a very efficient way to package a ring. Likewise, with variables, you’ll want to declare the data types according to the space requirements for efficient use of computer memory.

When it is important that code lines are not broken in the script, but the page width does not allow for their display without breaking, I use <=> to indicate that this line of code is to be continued, uninterrupted, on one line uninterrupted.

Declaration of variables

A computer program starts with the declaration of variables.

In PHP you do not have to declare a data type. A variable name in PHP is preceded with a $ sign. For example, $n=0; The string of text should be enclosed in either single or double quotation marks. For example:

$firstname=“Alexander’;

Or

$lastname=“Makedonski”;

$name=“Alexander Makedonski”;

As you may have noticed, a line of code in PHP is ended with a semicolon.

It’s always good practice to add comments when writing code, as they will enable you to better understand the meaning later. Also, if someone else reads or modifies your code, comments may be helpful. Comments must be preceded by two back slashes or placed between asterisks and backslashes:

/* this is code comment */

//this is another code comment

All PHP code blocks start with a "<?php” tag and ends with”? >" tag.

Basic Operators

Any computer language uses operators to calculate or compare variables, most of which are self-explanatory. For example, PHP uses + (plus), — (minus), * (multiplication), / (division), % (modulo) and "=" the assignment operator.

Let’s discuss the modulo operator. The modulo operator is used in finding the resultant remainder after one number has been divided into another. The following are a couple of examples to help you better understand:

The first example is 15% 5 = 0. As you can see, 5 divides evenly into 15 with no remainder, so the result we get is 0. Now let’s use 10% 7 = 3 as our second example. Because 7 divides into 10 once and leaves a remainder of 3, our answer must be 3.

30% 6 = 0 (30 — 5 * 6 = 30 30 — 30 = 0)

30% 7 = 2 (30 — 4 * 7 = 30 — 28 = 2)

30% 8 = 6 (30 — 3 * 8 = 30 — 24 = 6)

Comparison operators

$a == $b Equal TRUE if $a is equal to $b after type adjustment.

$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.

$a!= $b Not equal TRUE if $a is not equal to $b after type adjustment.

$a <> $b Not equal TRUE if $a is not equal to $b after type adjustment.

$a!== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type.

$a <$b Less than TRUE if $a is strictly less than $b.

$a> $b Greater than TRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.

$a> = $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Let’s see an example with = = = identical operator.

$a = “10”;

$b=10;

if ($a ==$b)

echo “a = b <br>”;

else

echo “a <> b <br>”;

If ($a === $b)

echo “a and b are identical <br>”;

else

echo “a and b are not identical <br>”;

Output:

a = b

a and b are not identical

$a and $b are equal because they equal 10, but they are not identical because $a is a string and $b is an integer.

$a = 9; Assignment: $a equals 9.

$a += 7; Addition-assignment: $a equals $a plus 7.

$a *= 4; Multiplication-assignment: $a equals $a multiplied by

4.

$a /= 3; Division-assignment: $a equals $a divided by 3.

$a.= 6; Concatenation-assignment: $a equals $a concatenated

with 6

Let’s write a simple code converting Fahrenheit to Celsius.

<?php

// $F is a temperature in Fahrenheit, $C is in Celsius

$F=80;

//The “echo” is a command that Output: s text to

//the browser

echo “F=”. $F.”<br>”;

// a formula to convert Fahrenheit to Celsius

$C = ($F — 32) * 5/9;

//Output: temperature in Celsius

echo “C=”. $C.”<br>”;

?>

Output:

F=80

C=26.6666666667

Please pay attention to “F=”. $F.’<br>‘on the code line echo; Here we concatenate 3 separate strings into one.

“F=”

$F

“<br>" — HTML break.

Two dots are placed between our three strings because dots are used to concatenate strings in PHP:

“F=”. $F. "<br>”;

The fact is that $F is not a string. It is an integer because it is equal to 80. If $F were equal to “80” it would be a string.

When we concatenate the $F variable between 2 strings, because PHP converts it to a string, there is no need to do anything further.

As I wrote earlier, a string of text can be enclosed in single quotation marks:

echo “F=”. $F.”<br>”;

To Output: a string of text, you can use the “print” command instead of the “echo” command.

However, in this case, you would use parentheses and single or double quotation marks.

print (“F=”. $F.”<br />”);

Or

print (“F=”. $F.”<br />”);

PHP variables are case sensitive, so $F is not the same as $f, and $lastname is not the same as $Lastname or $LASTNAME.

Let us say that we wish to use PHP to Output: a web page to a browser using the following HTML link:

<a href="http://www.yahoo.com">yahoo</a>

If we write

print (”<a href="http://www.yahoo.com">yahoo</a>");

we would receive an error message due to the use of double quotation marks in our HTML code. To avoid the error message, use single quotation marks for the print command as I’ve done in the following:

print (”<a href="http://www.yahoo.com">yanhoo</a>');

The same is true for an HTML input element:

echo '<input type=“text” name=“lname” value=“James”/>”;

or

print (”<input type=“text” name=“fname” value=“John”/>”);

One handy feature of the PHP code is the ability to include one file inside another. The creation of a website solely in HTML requires you to edit every single page of that website if you later wish to change the navigation, logo or footer. The use of PHP to create the web pages allows you to include one file with navigation or logo in every web page requiring you to edit only one file to later change the navigation or logo.

There are two commands to include the file in your PHP code:

include('top_menu.php’);

or

require("footer.php”);

or

require_once ("footer.php”);

The difference between the two is, when using the “include” command, if the file to be included does not exist, you will be given a warning message; however, the execution of the rest of the PHP code will not be interrupted. Conversely, when using the “required” command, if the required file is not found, a fatal error message is displayed, and the execution of the PHP code will cease. The require_once is similar to the required?? but it checks to include the footer.php file only once even if you write require_once ("footer.php”); twice.

Function

A function is a piece of code that performs a specific manipulation with variables and then returns the result from that manipulation. Functions are useful because they can be used multiple times over. There are PHP functions that are built-in, but a function can also be created by the user. Let’s create one that converts Fahrenheit to Celsius. The PHP function declaration begins with the word function to be followed by the function name, which should be one word. Several parameters can be given to a function, but a function can only return one parameter in the return statement. Multiple parameters are enclosed together in parentheses and separated by comas. The entire piece of code inside a function is enclosed in curly brackets.

In our example, we pass one parameter, a temperature in Fahrenheit, and return a temperature in Celsius.

function convertFtoC ($F) {

$C = round (($F — 32) * 5/9);

return $C;

}

Now to convert Fahrenheit to Celsius you must call your function and pass the temperature in Fahrenheit.

$T= convertFtoC (80);

echo $T.”<br>”;

The Output: will be 27

The round is a built-in PHP function. It will round 26.6666666667 to 27.

Variable Scope

Variables in the PHP code may have different scopes. They may be seen or accessed globally, anywhere on the current php page or only inside the function. Let us analyze the following code:

<?php

$greeting=“Hello!”;

function greetme ($name) {

echo $greeting.””. $name;

}

//function call

greetme (“John’);

?>

Output: John

At the beginning of the code, we assigned the “Hello” string to the $greeting variable. Then we defined the function with one parameter $name. Inside the function we concatenated the $name variable to the $greeting variable. Then we called the function and passed the name “John’ as a parameter.

You might expect the Output: would be “Hello John”, since $greeting equals “Hello”, but it’s “John”. “Hello” is not visible because the $greeting variable inside the function is not the same as outside. It’s local, and because we assigned no value to the local variable $greeting, the value we passed as a parameter is the only one visible.

Let us modify the function.

<?php

$greeting=“Good morning!”;

function greetme ($name) {

$greeting=“Hi There”;

echo $greeting.””. $name;

}

echo greetme (“John’);

echo "<br>”;

echo “Greeting=”. $greeting.”<br>”;

?>

Output:

Hi There John

Greeting=Good Morning

Inside the function we assigned the value “Hi There” to the local variable $greeting. As a result, the function will return “Hi There John”. However, because we printed the $greeting variable outside the function, the global variable $greeting value remains “Good Morning”.

Let us modify our code again.

<?php

$greeting=“Good Morning”;

function greetme ($name) {

global $greeting=“Hi There”;

echo $greeting.””. $name;

}

echo greetme (“John’);

echo "<br>”;

echo “Greeting=”. $greeting.”<br>”;

?>

Output:

Hi There John

Greeting=Hi There

In the above we’ve declared a global variable inside the function, using global. Then we assigned the value “Hi There” to the global $greeting variable.

We previously assigned “Good Morning” to the global variable $greeting outside the function. Then, inside the function, we assigned a global variable with the same name to the value “Hi There”. Now the global variable $greeting no longer has the value “Good Morning”, but rather “Hi There”. So, when we print the value of the global variable outside the function it displays, “Hi There”.

Static variable

A static variable is the same as a local variable, but it is not destroyed when the function execution is ended.

<?php

function greetme ($name) {

static $greeting=“Hi There”;

$greeting=$greeting.””. $name;

echo $greeting.”! <br>”;

}

greetme (“John’);

greetme (“John’);

greetme (“John’);

?>

Output:

Hi There John!

Hi There John John!

Hi There John John John!

The value of the static $greeting variable is changing after each function call because the $name variable is added to it each time.

Remove the static keyword and the Output: of the function will be the same in the second and the third call

<?php

function greetme ($name) {

$greeting=“Hi There”;

$greeting=$greeting.””. $name;

echo $greeting.”! <br>”;

}

greetme (“John’);

greetme (“John’);

greetme (“John’);

?>

Output:

Hi There John!

Hi There John!

Hi There John!

Passing parameters by value or by reference

At run time, the system assigns our declared variable to a memory location called a reference.

The reference to a variable can be accessed by preceding the identifier of a variable with an ampersand sign (&). The variable address is a hexadecimal number. As seen displayed in the following C++ code, on the first line we declare a pointer (*a) to a memory address. On the second line, we declare a variable (b) and assign its address to the pointer (a). And finally, on the last line, the content of the address of the memory location is displayed as a hexadecimal number.

int *a;

int b=7;

a = &b;

cout <<“The address of the memory location of b:"<<a <<endl;

Output: The address of the memory location of b: 0039FF15

In PHP you can pass the variable address to a function by preceding its name with an ampersand (&). Normally, when we pass a variable to a function, by default the system makes a copy of the variable and passes the copy to the function. The value of the copy may change inside the function, but the value of the original variable remains the same.

As reflected in the two examples below, when passing a variable by reference, the address of the variable is passed inside the function. So, if a new value is assigned to the address, the value of the original variable changes as well. In the first example, we pass variables by values; and in the second, we pass them by reference.

<?php

function switch_by_value ($k, $n) {

$temp=0;

$temp=$k;

$k=$n;

$n=$temp;

}

$a = 5;

$b= 7;

echo “By Value: <br>”;

echo “Before: a=”. $a. ' b=”. $b.”<br>”;

switch_by_value ($a, $b);

echo “After: a=”. $a. ' b=”. $b.”<br>”;

Output:

By Value:

Before: a=5 b=7

After: a=5 b=7

Notice that the values of the original variables (a) and (b) are not switched.

function switch_by_reference (&$k, &$n) {

$temp=0;

$temp=$k;

$k=$n;

$n=$temp;

}

$a = 5;

$b= 7;

echo “By Reference: <br>”;

echo “Before: a=”. $a. ' b=”. $b.”<br>”;

switch_by_reference ($a, $b);

echo “After: a=”. $a. ' b=”. $b;

?>

Output:

By Reference:

Before: a=5 b=7

After: a=7 b=5

Notice that the values of the original variables (a) and (b) are switched.

Useful string functions

PHP has many built-in string functions. String length can be determined with strlen () function.

$lastname=“Shakespeare”;

$len=strlen ($lastname);

echo “Length=”. $len.”<br>”;

Output: Length=11

The trim () function trims space characters from the beginning and the end of a string. This function is useful because a user may inadvertently enter space characters while typing in a login or password. To prevent this from occurring, trim every user input string as in the following example:

$lastname =' Shakespeare”;

echo “Before trim:”. strlen ($lastname).”<br>”;

$lastname=trim ($lastname);

echo “After trim:”. strlen ($lastname).”<br>”;

Output:

Before trim 13

After trim 11

As you can see, I’ve intentionally entered a space at the beginning and end of the last name and its length became longer by two characters. After trimming these spaces, the length was restored to 11 characters.

The string position function strpos () returns the position of the first occurrence of a substring in the string.

For example, echo strpos ($lastname, ‘sp’) will return 5.

You might expect it to return 6 because sp is in the 6th position; however, it returns 5

because the count starts at 0.

echo strpos ($lastname, “Shake’); will return 0.

After execution, echo strpos ($lastname, ‘shake’); nothing will be displayed in the browser because it returns Boolean false. Lower case ‘shake’ has not occurred in the “Shakespeare’. To confirm this, execute the following code:

if (strpos ($lastname, ‘shake’) ===false)

echo “return false <br>”;

Output: return false

The strpos is a case sensitive function. The stripos is a case insensitive function.

echo stripos ($lastname, ‘shake’); will return 5.

The strrpos () — Find the position of the last occurrence of a substring in a string.

echo strrpos ($lastname, ‘e’) will return 10.

The substr () function will return a substring of a string.

echo substr (“William Shakespeare’, 8); will return Shakespeare

echo substr (“William Shakespeare’, 8, 5); will return Shake.

It starts counting from 0 and returns that piece of substring starting from the 8th character.

The second parameter, if it is present, determines the substring length. This explains why

echo substr (“William Shakespeare’, 8, 5); will return Shake.

If the second parameter is not present, all that portion of string is returned.

This is why echo substr (“William Shakespeare’, 8); will return Shakespeare

The str_replace () is another important string function. This function replaces all occurrences of the search string with a replacement string.

For example, if a user entering text containing single or double quotation marks into a form, it can create problems with the database. To prevent this from happening, using the str_replace function, we can replace all occurrences of single quotation marks in the input text.

$comments=“this is comments with a ‘single quotation’ marks”;

echo “before str_replace:”. $comments.”<br>”;

$comments=str_replace (” ‘”, "&acute;”, $comments);

echo “after str_replace:”. $comments.”<br>”;

Output:

before str_replace: this is comments with a ‘single quotation’ marks after str_replace: this is comments with a “single quotation’ marks

When viewing the web page source, you will see that each single quotation mark has been replaced by the &acute; code.

PHP Array Functions

Arrays are used in any programming language. You can imagine an array as a long box with many identical compartments. Visualize it like this: |___|___|___|___|___|.

Whatever you place in a compartment is that particular compartment’s value. Let’s place the characters a, b, c, d and e in the following array of compartments: |_a_|_b_|_c_|_d_|_e_|

Now, to access any of these values, you’ll need to know which compartment the value is stored in. For example, ‘b’ is stored in the second compartment.

In most computer languages, array index counting starts from 0, not 1, meaning that the index of the first element of the array is 0, the index of the second element of the array is 1 and so on. In the following array of names, you see the indexes and values:

//declare an array of names

$names=array ();

$names [0] =“John”;

$names [1] =“George”;

$names [2] =“James”;

$names [3] =“Anna”;

$names [4] =“Robert”;

$names [5] =“John”;

$names [6] =“James”;

$names [7] =“George”;

$names [8] =“Maria”;

$names [9] =“Peter”;

$names [10] =“James”;

To display “Anna” you have to access the element (compartment) with the index 3. If you use the print command,

print ($names [3]);

The built-in function sizeof (array) returns the number of elements in an array. In this case,

$asize=sizeof ($names);

Or you can use the count function

$asize=count ($names);

To display all array values, we can use the for loop.

The for loop looks like this:

for ($i=0; $i <$asize; $i++)

print ($names [$i].”<br>”);

In the for loop, the $i variable is incremented from 0 to the value one less than the $asize value. If the array has 11 elements, the $sizeof () function will return 11. The $i variable will be incremented to 10 and then stops. You might assume that if $i stops at 10, and we have 11 elements, the last array element would not be displayed.

However, that assumption would be wrong because the first array element index is 0, the eleventh element will have index 10, and so our code will display the element index 10, which is the 11th element of the array.

There are many useful built-in functions for arrays. The code below demonstrates some of these:

The in_array () function returns true if the value exists in an array.

So, in the above array of names, in_array (“Anna’) will return True, but in_array (“Lidia’) will return False.

The sort function sorts an array in ascending order.

The rsort function sorts an array in reverse order.

The array_pop function removes and returns the last element of an array.

The array_push function adds an element to the end of array.

The array_unique function removes duplicate values from an array.

The print_r function prints an array.

The array_rand function selects a random array element.

The implode function converts an array into a string.

<?php

print (”<br> The sort function sorts array <br>”);

sort ($names);

//Get size of array

$asize=sizeof ($names);

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

//Check if it is female name put Mrs. prefix

//else put Mr. prefix

if (($names [$i] ==“Anna”) || ($names [$i]

==“Maria”))

{

print (“Hello Mrs.”. $names [$i].”<br>”);

}

else

{

print’ Hello Mr.”. $names [$i].”<br>”);

}

} //for

print (”<br>”);

?>

Output:

The sort function sorts an array

Hello Mrs. Anna

Hello Mr. George

Hello Mr. George

Hello Mr. James

Hello Mr. James

Hello Mr. James

Hello Mr. John

Hello Mr. John

Hello Mrs. Maria

Hello Mr. Peter

Hello Mr. Robert

<?php

echo “The array_unique function removes duplicate array values <br>”;

$array=array ();

$array=array_unique ($names);

foreach ($array as $key => $value) {

echo $key. "-”. $value. "<br>”;

}

print (”<br>”);

?>

Output:

The array_unique function removes duplicate values.

0-Anna

1-George

3-James

6-John

8-Maria

9-Peter

10-Robert

<?php

rsort ($array);

print (“The rsort function sorts an array in reverse order <br>”);

foreach ($array as $key => $value) {

echo $key. "-”. $value. "<br>”;

}

?>

Output:

The rsort function sorts an array in reverse order

0-Robert

1-Peter

2-Maria

3-John

4-James

5-George

6-Anna

<?php

print (”<br> The array_pop () functions returns the last element. <br>”);

$lastelement=array_pop ($array);

print (”<br> The last element=”. $lastelement.”<br>”);

?>

Output:

The array_pop () function returns the last element

The last element=Anna

print (”<br> Array after calling the array_pop ().

The last element removed. <br> <br>”);

foreach ($array as $key => $value) {

echo $key. "-”. $value. "<br>”;

}

Output:

Array after calling array_pop (): The last element removed

0-Robert

1-Peter

2-Maria

3-John

4-James

5-George

The array_push function adds elements to the end of an array.

The print_r prints array function prints array key — value pairs.

<?php

array_push ($array, “Chris”, “Colin”);

print_r ($array);

?>

Array after calling array_push ($array, “Chris”, “Colin”)

and print_r functions: Chris and Colin are added to the end of the array.

Output:

Array ([0] => Robert [1] => Peter [2] => Maria [3] => John [4] => James [5] => George [6] => Chris [7] => Colin)

The array_rand ($array) function returns random array index.

$random=array_rand ($array);

print (”<br> print array element by random

index <br>”);

print (”<br> Random element=”. $array [$random].”<br>”);

Output:

print array element by random index

Random element=Colin

<?php

$string=implode ($array);

print (”<br> Array is imploded in a string: <br>”);

print ($string);

?>

Array is imploded in a string:

RobertPeterMariaJohnJamesGeorgeChrisColin

The for loop

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

print ($i.”<br>”);

}

The $i variable is local because it is defined inside the loop. However, if you try to Output: the $i variable outside the loop, its value will be 10.

Break and Continue

Break; statement breaks out of the loop. Loop execution stops.

$names [0] =“Anna”;

$names [1] =“George”;

$names [2] =“James”;

$names [3] =“James”;

$names [4] =“John”;

$names [5] =“Maria”;

$names [6] =“Peter”;

$names [7] =“Robert”;

for ($i=0; $i <sizeof ($names); $i++) {

if ($names [$i] == “John”)

Break;

print ($names [$i].”<br>”;

}

The loop above will print the names:

Anna

George

James

James

and then stops. The names John, Maria, Peter and Robert will not be printed.

Continue; statement makes the loop skip iteration. See the following continue code example:

for ($i=0; $i <sizeof ($names); $i++) {

if ($i == 0)

print ($names [$i].”<br>”);

else

{

if ($names [$i-1] == $names [$i])

continue;

print ($names [$i].”<br>”);

}

}

Output:

Anna

George

James

John

Maria

Peter

Robert

In line if ($names [$i-1] == $names [$i]) we check if a previous name equals a current name. In the first iteration, we do not have a previous name, so we print a name without checking for a duplicate.

Starting from the second iteration, when $i => 1 we check whether a previous name is equal to the current one. If it is, we skip the loop.

As a result, the duplicate name is not printed. The break and continue may be used in all other loops.

The foreach loop

To use the for loop for an array you have to know how many items the array has. Sometimes, it is more convenient to use the foreach loop. The Foreach loop has the following syntax:

foreach (array_expression as $value)

statement

http://php.net/manual/en/control-structures.foreach.php

If you have an array of names ($names) and you want to greet each person, use the foreach loop to avoid having to know how many names are in the array.

foreach ($names as $aname)

echo “Hello,”. $aname.”! <br>”;

Output:

Hello, John!

Hello, George!

Hello, James!

Hello, Anna!

Hello, Robert!

Hello, John!

Hello, James!

Hello, George!

Hello, Maria!

Hello, Peter!

Hello, James!

In the foreach loop we can read and display not only a value of the array element but its key as well.

foreach (array_expression as $key => $value)

statement

foreach ($names as $key=> $aname)

echo $key.” Hello,”. $aname.”! <br>”;

Output:

0 Hello, John!

1 Hello, George!

2 Hello, James!

3 Hello, Anna!

4 Hello, Robert!

5 Hello, John!

6 Hello, James!

7 Hello, George!

8 Hello, Maria!

9 Hello, Peter!

10 Hello, James!

The number is the array element’s index or key.

The while Loop

The ‘while loop’ is used in many programming languages. A code inside a while loop is executed while a condition is true.

When using the while loop, make sure that your condition will become false and the loop stops. Otherwise you will be continuously stuck in the loop.

Let us print our array using the while loop.

while ($i <$asize) {

print (“Hello, ".name [$i].”<br />”;

$i ++;

}

Output:

Hello, John!

Hello, George!

Hello, James!

Hello, Anna!

Hello, Robert!

Hello, John!

Hello, James!

Hello, George!

Hello, Maria!

Hello, Peter!

Hello, James!

If and else statement

The if… else statement is used to execute different pieces of code under different conditions.

It has the following construction:

If (conditions) {

Do this.

} elseif (different condition) {

Do that.

} else {

Do something else.

}

Let us create a function that will print a message depending on temperature.

function weather ($F) {

if ($F> 78)

$message=“It is too hot!”;

elseif ($F <65)

$message=“It is too cold!”

else

$message=“Today is nice outside!”;

Return $message.”<br />”;

}

Let us call the function

echo weather (80);

Output: will be “It is too hot!”;

echo weather (60);

Output: will be “It is too cold!”;

echo weather (70);

Output: will be =“Today is nice outside!”;

Switch statement

The switch statement has the following syntax:

switch (variable) {

case label1:

code to be executed if variable =label1;

break;

case label2:

code to be executed if variable =label2;

break;

default:

code to be executed if variable is not equal any label;

}

A Switch Example:

$temperature_C=100;

Switch ($temperature_C) {

Case: 0

$message=“Water freezing point.”;

Break;

Case: 100

$message=“Water boiling point!”:

Break;

Default:

$message=“Neither freezing nor boiling point.”;

}

If we pass in our switch statement variable with the value of 100 we will get Output: “Water boiling point!”

If we pass 0 we will get Output: =“Water freezing point.”

Otherwise, we will get Output: “Neither freezing nor boiling point.”

List

List is a language construction. It is used to assign a list of variables in one operation.

In the line below, I assign array $names from the array example above to a list of variables.

list ($name1, $name2, $name3, $name4, $name5, $name6) = $names;

print ($name5); will print John because it is the 5th name in the array.

Multidimensional Arrays

An example of a two-dimensional array is plane seats. A plane has rows identified by numbers and a few seats in a row identified by letters A, B, C, D, E, and F.

Let us imagine that we have 7 rows with 6 seats in each of the rows. Define an array of seats in a row as $s. Then in two for loops we can create an array of all seats.

$s=array (“A”, “B”, “C”, “D”, “E”, “F”);

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

$row = $i+1;

for ($j=0; $j <6; $j++) {

$seats [$i] [$j] =$row.$s [$j];

print ($seats [$i] [$j]);

if (($j % 5 ==0) && ($j> 0))

print (”<br>”);

}

}

In an inner J loop, we assign a seat value to the two-dimensional array.

$row = $i +1 because $i starts with 0 and the row starts with 1.

Бесплатный фрагмент закончился.
Купите книгу, чтобы продолжить чтение.
электронная
от 432
печатная A5
от 645