php programming – Cyber Hyena https://cyberhyena.net web security crypto currencies and learn programming Tue, 16 Mar 2021 18:38:44 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.6 https://cyberhyena.net/wp-content/uploads/2020/11/New-Project-2020-11-24T165858-150x126.png php programming – Cyber Hyena https://cyberhyena.net 32 32 free PHP programming course E5 learn to code https://cyberhyena.net/blog/2021/03/16/free-php-programming-course-e5-learn-to-code/ https://cyberhyena.net/blog/2021/03/16/free-php-programming-course-e5-learn-to-code/#respond Tue, 16 Mar 2021 18:38:44 +0000 https://cyberhyena.net/?p=268 FREE php course Lecture #5: Selection Structure  Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop (discussed in a later lecture), a conditional statement, or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, […]

The post free PHP programming course E5 learn to code appeared first on Cyber Hyena.

]]>
0 0
Read Time:14 Minute, 55 Second

FREE php course Lecture #5: Selection Structure  Any PHP script is built out of a series of statements. A statement can be an assignment, a function call,
a loop (discussed in a later lecture), a conditional statement, or even a statement that does nothing (an
empty statement). Statements usually end with a semicolon. In addition, statements can be grouped
into a statement-group by encapsulating a group of statements with curly braces. A statement-group is
a statement by itself as well.

Control Statements … FREE php course

A control statement is a statement that is used to alter the continuous sequential invocation of
statements. It is a statement that controls when and how one or more other statements are executed. In
PHP, statements fall into three general types:

Assignment, where values, usually the results of calculations, are stored in variables (as discussed
in previous lecture).
Input / Output, data is read in or printed out.
Control, the program makes a decision about what to do next.

Unless being specified, statements in a PHP program are executed one after another in the order in
which they are written, this is known as sequential execution. However, programs can be much more
useful if the programmer can control the sequence in which statements are run. You will soon find out
that there will always be a need to jump off the linear sequence. A transfer of control occurs when the
next statement to be executed are specified by the programmer, instead of the immediate succeeding
statement.

As a programmer, the control of statement sequence is actually the arrangement of:

• selecting between optional sections of a program.
• repeating important sections of the program.

All PHP programs are thus written in terms of three forms of control: sequence, selection, and
repetition.

Conditional Statements

A conditional statement is used to decide whether to do something at a special point or to decide
between two courses of action. A conditional statement chooses among alternative actions in a PHP
program. The if statement performs (selects) an action based on a tested condition.

A condition is an expression with a Boolean value (TRUE or FALSE) that is used for decision making. For example,

$x >= 3

In this statement, the value of variable $x can be anything, such as 1, 2, 8, 110, 224, and so on. This
expression is then sometimes true, sometime false depending on the current value of $x .

Conditional statements can be as simple as the above one or they can be compound statements as
shown below:

($x >= 3) AND ($x <= 15)

For example:

<?php
$s = 6;
$t = 5;
if ($s>4 AND $t>4) {echo “TRUE!”; }
?>

The output is TRUE! because both conditions $s>4 and $t>4 are true.

 

The if statement …..,, FREE php course

The if statement is one of the most important features of many languages, PHP included. It allows for
conditional execution of code fragments. PHP’s if statement is similar to that of the C programming
language.

In PHP, many conditional statements (also known as selection statements) begin with the keyword if,
followed by a condition in parentheses.

The statement(s) of execution are grouped together between curly brackets { }. Such a grouping is called a compound statement or simply a block. The syntax
then looks like:

if ( condition )
{ execution }

where condition is an expression that is evaluated to its Boolean value. If expression evaluates to
TRUE, PHP will execute the statement, and if it evaluates to FALSE, PHP ignores it.
The following test decides whether a student has passed an exam with a passing mark of 60. Notice
that it is possible to use the if part without the else part.

<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 60) // test if the value of user entry >= 60
{ echo “Pass!”; } // display Pass!
?>

The following example checks whether the current value of the variable $hour is less than 12 and the
echo statement displays its message only if this is the case (namely $hour < 12 is true).

<?php
$hour = date(“H”); //get the current hour value
if ($hour < 12) {
echo “Good morning!”;
}
?>

The if … else statement

The above example has a logic problem. It specifies what to execute when the $grade is greater than or
equal to 60, but it did not specify what to do if the $grade is less than 60. To solve this logic problem,
use the if … else statement. The if statement performs an indicated action (or sequence of actions) only
when the condition is tested to be true; otherwise the execution is skipped. The if … else statement
performs an action if a condition is true and performs a different action if the condition is false.
The else statement extends an if statement to execute a statement in case the expression in the if
statement evaluates to FALSE. The syntax looks like:

if ( condition )
{ execution 1 } // do this when condition is TRUE
else
{ execution 2 } // do this when condition is FALSE

You can now rewrite the above example to:

<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 60) // condition
{ echo “Pass!”; } // execution 1
else
{ echo “Fail!”; } // execution 2
?>

 

The else statement is only executed if the “if” expression is evaluated to FALSE as well as any elseif
expressions that evaluated to FALSE.

Often you need to have more than one statement to be executed conditionally. Of course, there is no
need to wrap each statement with an if clause. Instead, you can group several statements into a
statement group.

If statements can be nested infinitely within other if statements, which provides you with complete
flexibility for conditional execution of the various parts of your program.

The elseif statement ….. FREE php course

Sometimes a programmer needs to make a decision based on several conditions. This can be done by
using the elseif variant of the if statement.

The elseif statement, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if
expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if
the elseif conditional expression evaluates to TRUE.

As soon as one of these conditions yields a true result, the following statement or block is executed and
no further comparisons are performed.

There may be several elseif’s within the same if statement. The first elseif expression (if any) that
evaluates to TRUE would be executed. In PHP, you can also write else if (in two words) and the
behavior would be identical to the one of elseif (in a single word). The syntactic meaning is slightly
different, but the bottom line is that both would result in exactly the same behavior.
The elseif statement is only executed if the preceding if expression and any preceding elseif
expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

In the following example we are awarding grades depending on the exam result.

<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 90)
{ echo “A”; }
elseif ($grade >= 80)
{ echo “B”; }
elseif ($grade >= 70)
{ echo “C”; }
elseif ($grade >= 60)
{ echo “D”; }
else
{ echo “F”; }
?>

In this example, all comparisons test a single variable called result. In other cases, each test may
involve a different variable or some combination of tests. The same pattern can be used with more or
fewer elseif’s, and the final lone “else” may be left out. It is up to the programmer to devise the correct
structure for each programming problem.

The if…then statement can also be used to handle HTML form in one single PHP script (a later lecture
will discuss this topic in details). For example:

<?php
if ($_POST) { // if the form is filled out
$x = $_POST[“vofx”];
if ($x>=5) { echo “x is greater than or equal to 5!”; }

else { echo “x is less than 5!”; }
}
else { // otherwise display the form
?>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”>
Enter a value for <i>x</i>:
<input type=”text” name=”vofx” size=5>
<input type=”submit” value=”Check”></form></p>
<?php
}
?>

The $_POST expression is evaluated when the script is loaded to determine whether or not the form
fields (a textbox) has been filled in. If so, the script ignores the else part and processes the user input. If
not, the script displays only a form for the user to fill in.

if ($_POST) { // if the form is filled out
…… }
else { // otherwise display the form
?>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”>
……
</form>
<?php
}
?>

Notice that it uses the $_SERVER[‘PHP_SELF’] system variable to send the user inputs to itself.

Alternative syntax ….. FREE php course

PHP offers an alternative syntax for some of its control structures. the basic form of the alternate
syntax is to change the opening brace to a colon (:) and the closing brace to endif. For example:

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block “A is equal to 5″ is nested within an if statement written in the
alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and
else in the alternative format.

<?php
if($a > $b):
echo $a.” is greater than “.$b;
elseif($a == $b): // Note the combination of the words.
echo $a.” equals “.$b;
else:
echo $a.” is neither greater than or equal to “.$b;
endif;

?>

Note that elseif and else … if will only be considered exactly the same when using curly brackets as in
the above example. When using a colon to define your if/elseif conditions, you must not separate else if
into two words or PHP will fail with a parse error.

Problem of complexity

When writing a PHP program, you may have to compare the same variable (or expression) with many
different values, and execute a different piece of code depending on which value it equals to. You can
do so with nested if … else statements, but it will increase the complexity of your program. Consider
the following example:

<?php
$x= date(“w”); //number of the day of the week; 0 for Sunday
if ($x == 0) { echo “Sunday”; }
elseif ($x == 1) { echo “Monday”; }
elseif ($x == 2) { echo “Tuesday”; }
elseif ($x == 3) { echo “Wednesday”; }
elseif ($x == 4) { echo “Thursday”; }
elseif ($x == 5) { echo “Friday”; }
elseif ($x == 6) { echo “Saturday”; }
else { echo “No such option!”; }
?>

This above code will display different value according to the number of the weekday—0 for Sunday, 1
for Monday, and so on. If the number is not in {0, 1, 2, 3, 4, 5, 6}, then it will display “No such
option!”. This example use only one block of code to handle 8 conditions, which certainly increase the
complexity (imaging you have 20 conditions!). This is exactly what the switch statement is for.

The switch..case Statement

The switch statement is similar to a series of if statements on the same expression, but it is a better way
of writing a program when a series of if..else’s occurs. It is important to understand how the switch
statement is executed in order to avoid mistakes. The switch statement executes line by line (actually,
statement by statement). The switch/case statement syntax is as follows:

switch (expression) {
case value1:
statement(s);
break;
case value2:
statement(s);
break;
………..
………..
default:
statement(s);
break;
}

where the case expression may be any expression that evaluates to a simple type, that is, integer or
floating-point numbers and strings. Arrays or objects cannot be used here unless they are not
referenced to a simple type.

In a switch statement, the condition is evaluated only once and the result is compared to each case
statement. In an elseif statement, the condition is evaluated again. If your condition is more
complicated than a simple compare and/or is in a tight loop, a switch may be faster. The advantage of
using switch statement is to simplify the complexity of if…else’s.

The following two examples show two different ways to test for the same conditions – one uses a series
of if and elseif statements, and the other uses the switch statement.

It is important to understand how the switch statement is executed in order to avoid mistakes. The
switch statement executes line by line (actually, statement by statement). In the beginning, no code is
executed. Only when a case statement is found with a value that matches the value of the switch
expression does PHP begin to execute the statements. PHP continues to execute the statements until
the end of the switch block or the first time it sees a break statement. The break construct is used to
force the switch code to stop. PHP will continue to execute the statements until the end of the switch
block or the first time it sees a break statement. If you don’t include a break statement at the end of a
case’s statement list, PHP will go on executing the statements of the following case.

Consider the following examples;

FREE php course
FREE php course

Only when a case statement is found with a value that matches the value of the switch expression does
PHP begin to execute the switch statements.

Notice that a special case is the default case. This case matches anything that doesn’t match any other
cases, and should be the last case statement.

In PHP, the statement list for a case can also be empty, which simply passes control into the statement
list for the next case. The use of default case is also optional. In the following example, only when the
weekday is Tuesday will a user see an output.

 

<?php
$i= date(“w”);
switch ($i) {
case 0:
case 1:
case 2:
echo “It is Tuesday, and you just won the prize!”;
break;
case 3:
case 4:
case 5:
case 6:
}
?>

In PHP, the switch structure allows usage of strings. For example,

<?php
switch ($i) {
case “apple“:
echo “i is apple”;
break;
case “bar“:
echo “i is bar”;
break;
case “cake“:
echo “i is cake”;
break;
}
?>

The alternative syntax for control structures is supported with switches. For example:

<?php
switch ($i):
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i is not equal to 0, 1 or 2”;
endswitch;
?>

It is possible to use a semicolon ( ; )instead of a colon ( : )after a case. For example:
<?php
switch($beer)
{
case ‘Tuborg’;
case ‘Carlsberg’;
case ‘Heineken’;
echo ‘Good choice’;
break;
default;
echo ‘Please make a new selection…’;
break;

}
?>

 

Review Questions

1. The result of the following calculation is __.

<?php echo (9 != 7); ?>

A. 1
B. 0
C. True
D. False

2. The result of the following calculation is __.

<?php echo !(6 <= 4); ?>

A. 1
B. 0
C. True
D. False

3. Given the following code segment, what is the output?

<?php
$x = 3;
if ($x > 3) { echo “Correct!”; }
else { echo “Incorrect!”; }
?>

A. Correct!
B. Incorrect!
C. True
D. False

4. Given the following code segment, what is the output?

<?php
$x = 6;
if (($x > 3) AND ($x <=7)) { echo “Correct!”; }
else { echo “Incorrect!”; }

?>

A. Correct!
B. Incorrect!
C. True
D. False

5. The result of the following calculation is __.

<?php
$i=6;
if ($i>=4) {
if ($i=5) { echo $i; }
else { echo $i–;} }
else { echo $i++; }
?>

A. 4
B. 5

C. 6
D. 3

6. The result of the following calculation is __.

<?php
$i=3;
if ($i>=4) {
if ($i=5) { echo $i; }
else { echo $i–; } }
else { echo ++$i; }
?>

A. 4
B. 5
C. 6
D. 3

7. If the value of $i is 0, what is output?

<?php
switch ($i) {
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i equals 3”;
break;
}
?>

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3

8. If the value of $i is 3, what is output?

<?php

switch ($i) {
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i equals 3”;
break;
}
?>

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3

9. If the value of $i is 7, what is output?

<?php
switch ($i) {
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i equals 3”;
break;
}
?>

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3

10. If the value of $i is 0, what is output?

<?php
switch ($i) {
case 0: echo “i equals 0”;
case 1: echo “i equals 1”;
case 2: echo “i equals 2”;
default: echo “i equals 3”;
}
?>

A. i equals 0
B. i equals 0i equals 1
C. i equals 0i equals 1i equals 2
D. i equals 0i equals 1i equals 2i equals 3

full lectures HERE

FREE php course

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

The post free PHP programming course E5 learn to code appeared first on Cyber Hyena.

]]>
https://cyberhyena.net/blog/2021/03/16/free-php-programming-course-e5-learn-to-code/feed/ 0
free PHP programming course E4 learn to code https://cyberhyena.net/blog/2021/03/16/free-php-programming-course-e4-learn-to-code/ https://cyberhyena.net/blog/2021/03/16/free-php-programming-course-e4-learn-to-code/#respond Tue, 16 Mar 2021 18:13:05 +0000 https://cyberhyena.net/?p=264 FREE php course Lecture #4 PHP Arrays An array in PHP is actually an ordered list that stores multiple values. All items in the list have at least one thing in common that set the sequence of values of the item. For example, there are four seasons in a year. Winter must come before spring, […]

The post free PHP programming course E4 learn to code appeared first on Cyber Hyena.

]]>
0 0
Read Time:10 Minute, 59 Second

FREE php course Lecture #4 PHP Arrays An array in PHP is actually an ordered list that stores multiple values. All items in the list have at
least one thing in common that set the sequence of values of the item. For example, there are four
seasons in a year. Winter must come before spring, spring must come before summer, and more.
“Season” is the name of array, which contains four items, spring, summer, fall, and winter, in
sequence.

In PHP, it’s easy to create and initialize PHP arrays. There are two methods to choose from, and
we’ll be discussing both of them in this lecture. You can
create an array with the array identifier.
create an array with the array() function.

 

Create an array with the array identifier ..– FREE php course

The simplest way to create a PHP array is to use the array identifier, which is a set of empty square
brackets. For example:

$season[0]=”Spring”;
$season[1]=”Summer”;
$season[2]=”Fall”;
$season[3]=”Winter”;

The syntax is:

ArrayName[index]=value

By default, the index numbers start at zero, and arrays are assumed to be zero-based. This means
that the index number of the last element is typically one less than the number of elements. In other
words, if an array has four elements, the last value will be referenced as $season[3].

You can create an array, in PHP, by simply assigning values. For example:

$season[]=”Spring”;
$season[]=”Summer”;
$season[]=”Fall”;
$season[]=”Winter”;

PHP will automatically assign the index value for each element in the array. Try the following two
examples; they will yield the same results.

free php course
free php course

The output for both examples will look like:

Apple :1st item.
Tangerine : 4th item.

Create an array with the array() function …,,, FREE php course

In PHP, you can specify an array with array(). This is the method of choice when you have multiple
values to assign at one time. For example:

$season = array(“Spring”,”Summer”,”Fall”,”Winter”);

Each element is surrounded by quotes and separated by commas. The number of elements is
variable, so you can specify as many elements as you need to initialize the array.

For example:

<?php
$season = array(“Spring”,”Summer”,”Fall”,”Winter”);
echo $season[2] . ‘($season[2]) gets the 3rd item.’;
echo $season[3] . ‘($season[3]) gets the 4th item.’;
?>

will yield the following output:

Fall($season[2]) gets the 3rd item.Winter($season[3]) gets the 4th item.

Be sure to review the previous section to understand why the $season[2] value enclosed by single
quotes (‘) are escaped.

Defining the starting index value

By default, PHP arrays are zero-based. This means that the index value for the last element is
always one less than the total number of elements. If you have an array of all 50 US states, the first
element would be $states[0], and the last one will be accessed as $states[49]. If you’d like to change
the default behavior, use the “=>” operator.

For example:

$state = array(1 => “Alabama”, “Alaska”, “California”);

Consequently the first element, “Alabama”, would be accessed as $state[1] instead of the default
$state[0]. Compare the following codes and their results.

<?php
$state = array(1 => “Alabama”, “Alaska”, “California”);
echo $state[0];
?>

The output is Some kind of error message like “Undefined offset: 0”. Now try,

<?php
$state = array(1 => “Alabama”, “Alaska”, “California”);
echo $state[1];
?>

The output is:

Alabama

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.

All the above examples are numeric array. It is time to move on to associative array.

 

Creating Associative Arrays in PHP

When you create a simple PHP array, the starting index value is zero by default. However, you can
use string values as the index for each element in the array. When a PHP array uses strings for the
index values, it is known as an associative array.

Option 1: Create associative arrays with the array() function

To create an associative array in PHP, the easiest way is to use the array() function. However,
unlike a simple PHP array, an associative array in PHP needs both the index value, known as the
key, and the value of the element, known as the value. These are often referred to as key-value
pairs. Here’s an example:

$StateCapital = array(“AL”=> “Montgomery”, “LA”=> “Baton Rouge”,
“TX”=> “Austin”);

The example uses the two letter abbreviation for Alabama, Louisiana, and Texas as the key, or
index value. The capitals for those states, Montgomery, Baton Rouge, and Austin, are the values.
Notice that keys and values are separated by ‘=>’, and each key-value pair is separated by commas.

 

Option 2: Create associative arrays with the array identifier

Another way to create associative arrays in PHP is to use the array identifier.

$StateCapital[“AL”] = “Montgomery”;
$StateCapital[“LA”] = “Baton Rouge”;
$StateCapital[“TX”] = “Austin”;

For example:

<?php
$gender[“F”]=”Female”;
$gender[“M”]=”Male”;
$gender[“U”]=”Unidentifiable”;
echo “Jennifer Lopez is ” . $gender[“F”] .”!”;
?>

will yield the following output:

Jennifer Lopez is Female!
The following will yield “Bill Clinton is Male!”:

<?php
$gender = array(“F”=>”Female”, “M”=>”Male”, “U”=>”Unidentified”);
echo “Bill Clinton is ” . $gender[“M”] .”!”;
?>

Note that you can use both methods on the same array to add new elements.

$StateCapital = array(“AL”=> “Montgomery”, “LA”=> “Baton Rouge”,
“TX”=> “Austin”);
$StateCapital[“CA”] = “Sacramento”;

Consider the following example, the $StateCapital[“CA”] element is added after the array is created,
and the output is Sacramento.

<?php
$StateCapital = array(“AL”=> “Montgomery”, “LA”=> “Baton Rouge”,
“TX”=> “Austin”);
$StateCapital[“CA”] = “Sacramento”;
echo “The state capital of California is ” . $StateCapital[“CA”];
?>

One thing to keep in mind is that your keys, or index values, should be short and meaningful. Not
only will it be easier to maintain and modify your PHP script, but the script will also run more efficiently.

Another good thing to remember is not to access an associative array value within a string. Since the
keys and values are enclosed in double quotations, they can’t be embedded within a string. Instead,
use the concatenation operator to combine the string values.

Array is very useful to the design of dynamic web site. The following PHP code will randomly
display different graphics with hyperlink. Portal web sites, such as MSN.com and Yahoo.com, use
these techniques to randomly display advertisement on their sites.

<?php
$r = rand(0,9); //using rand() to generate random number
$graphic = array( //array of graphic file name
“01.gif”,
“02.gif”,
“03.gif”,
“04.gif”,
“05.gif”,
“06.gif”,
“07.gif”,
“08.gif”,
“09.gif”,
“10.gif”,
);
//use concatenation operator to combine file name to web site URL
$image =”http://www.mysite.com/images/” . $graphic[$r];
$url = array( // array of sites to link with each graphic
“http://www.cnn.com”,
“http://www.nbc.com”,
“http://www.abc.com”,
“http://www.fox.com”,
“http://www.mtv.com”,
“http://www.hbo.com”,
“http://www.pbs.com”,
“http://www.tnt.com”,
“http://www.tmc.com”,
“http://www.upn.com”,
“http://www.cbs.com”
);
echo “<a href=$url[$r]>”;
echo “<img src=$image border=0></a>”;
?>

Note: When you visit this site, click “Refresh” on the web browser toolbar to see how the code
displays different graphics dynamically.

Multi-Dimensional Arrays

PHP arrays can contain arrays. In other words, a multidimensional array is an array except that
holds other arrays as a value (in the regular key=>value pair of an array), which in turn hold other
arrays as well. For example, the following code creates three arrays: $SF, $Action, and $Romance.

$SF = array(“2001”, “Alien”,”Terminator”);
$Action = array(“Swing Girls”,”Premonition”,”Infection”);
$Romance = array(“Sleepless in Seattle”,”You’ve Got Mail”,”All of Me”);

A multidimensional array however, will contain another array as a possible value; for example, the $genre super-array contains all the three arrays.

<?php
$genre = array (
“SF” => array(“Star Wars”, “Alien”,”Terminator”),
“Action” => array(“Swing Girls”,”Premonition”,”Infection”),
“Romance” => array(“Sleepless in Seattle”,”You’ve Got
Mail”,”All of Me”)
);
print_r($genre);
?>

The “SF”, “Action”, and “Romance” are three individual arrays, but they are now elements to the
“genre” array. So the output of the above code looks:

Array
(
[SF] => Array
(
[0] => Star Wars
[1] => Alien
[2] => Terminator
)
[Action] => Array
(
[0] => Swing Girls
[1] => Premonition
[2] => Infection
)
[Romance] => Array
(
[0] => Sleepless in Seattle
[1] => You’ve Got Mail
[2] => All of Me
)
)

The above sample output shows the hierarchy of the genre array and its element arrays. You can
interpret the hierarchy using the format of: $genre[“SF”][0] = “Star War”. Formally, the
syntax is:

parentArrayName[“childArrayName”][“childElementKey”];

The following example further explains how to display values of each of the elements.

<?php
$genre = array (
“SF” => array(“Star Wars”, “Alien”,”Terminator”),
“Action” => array(“Swing Girls”,”Premonition”,”Infection”),
“Romance” => array(“Sleepless in Seattle”,”You’ve Got
Mail”,”All of Me”)
);
echo $genre[“SF”][0] . “<br />”;
echo $genre[“SF”][1] . “<br />”;
echo $genre[“SF”][2] . “<br />”;
echo $genre[“Action”][0] . “<br />”;

cho $genre[“Action”][1] . “<br />”;
echo $genre[“Action”][2] . “<br />”;
echo $genre[“Romance”][0] . “<br />”;
echo $genre[“Romance”][1] . “<br />”;
echo $genre[“Romance”][2] . “<br />”;
?>

The same format applies to number-based array. For example:

<?php
$lists = array ( 1 => array( 12, 14, 16), 2 => array(11, 13, 15) );
print_r($lists);
?>
The output looks,
Array
(
[1] => Array
(
[0] => 12
[1] => 14
[2] => 16
)
[2] => Array
(
[0] => 11
[1] => 13
[2] => 15
)
)
To display each value, use:

<?php
$lists = array ( 1 => array( 12, 14, 16), 2 => array(11, 13, 15) );
echo $lists[“1”][0] . “<br>\n”;
echo $lists[“1”][1] . “<br>\n”;
echo $lists[“1”][2] . “<br>\n”;
echo $lists[“2”][0] . “<br>\n”;
echo $lists[“2”][1] . “<br>\n”;
echo $lists[“2”][2] . “<br>\n”;
?>

Review Questions .., FREE php course

1. Given the following code, what is the output?

<?php
$n = array(1, 2, 3, 4);
echo $n[3];
?>

A. 1
B. 2
C. 3
D. 4

2. Given the following code, what is the output?

<?php
$n = array(1, 2, 3, 4);
echo $n[0]+$n[3];
?>

A. 5
B. 6
C. 7
D. 8

3. Given the following code, what is the output?

<?php
$a[] = 1;
$a[] = 2;
$a[] = 3;
$a[] = 4;
echo $a[2];
?>

A. 1
B. 2
C. 3
D. 4

4. Given the following code, what is the output?

<?php
$a[2] = 1;
$a[3] = 2;
$a[6] = 3;
$a[9] = 4;
echo $a[2];
?>

A. 1
B. 2
C. 3
D. 4

5. Given the following code:

<?php
$course[“cis245”] = “Perl Programming”;
$course[“cis246”] = “PHP Programming”;
$course[“cis247”] = “Python Programming”;
$course[“cis248”] = “Plank Programming”;
?>

which generate the following output?

PHP Programming

A. <?php print $course[“cis245”]
B. <?php print $course[“cis246”]
C. <?php print $course[“cis247”]
D. <?php print $course[“cis248”]

6. Given the following code,

<?php
$fruit = array(“A” => “Apple”,
“B” => “Banana”,
“G” => “Grape”,
“O” => “Orange”); ?>

which generate the following output?

I like banana!

A. print “I like ” + $fruit[“B”] . “!”;
B. print “I like ” . $fruit[“B”] . “!”;
C. print “I like ” $fruit[“B”] “!”;
D. print “I like ” + $fruit[“B”] + “!”;

7. Given the following code, which is the correct output?

<?php
$state = array(1 => “Alabama”, “Alaska”, “California”, “Nevada”);
echo $state[3];
?>

A. Alabama
B. Alaska
C. California
D. Nevada

8. Given the following code, which combination can yield a result of 10?

<?php $x = array( 9, 6, 4, 2, 5, 8, 9); ?>

A. $x[3] + $x[5];
B. $x[0] + $x[4] – $x[2];
C. $x[2] * $x[4];
D. $x[1] + $x[6];

9. Given the following code, which displays the value 99?

<?php $x = array ( 1 => array( 101, 102), 2 => array(100, 99) ); ?>

A. echo $x[“1”][0];
B. echo $x[“1”][1];
C. echo $x[“2”][0];
D. echo $x[“2”][1];

10. Given the following code, which displays the value Infection?

<?php
$genre = array (
“SF” => array(“Star Wars”, “Alien”,”Terminator”),
“Action” => array(“Swing Girls”,”Premonition”,”Infection”),
“Romance” => array(“Sleepless in Seattle”,”You’ve Got
Mail”,”All of Me”)
); ?>

A. echo $genre[“Action”][0] . “<br />”;
B. echo $genre[“Action”][1] . “<br />”;

C. echo $genre[“Action”][2] . “<br />”;
D. echo $genre[“Action”][3] . “<br />”;

FULL LIST OF LECTURSE HERE

FREE php course

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

The post free PHP programming course E4 learn to code appeared first on Cyber Hyena.

]]>
https://cyberhyena.net/blog/2021/03/16/free-php-programming-course-e4-learn-to-code/feed/ 0
free PHP programming course E3 learn to code https://cyberhyena.net/blog/2021/03/12/free-php-programming-course-e3-learn-to-code/ https://cyberhyena.net/blog/2021/03/12/free-php-programming-course-e3-learn-to-code/#respond Fri, 12 Mar 2021 21:43:50 +0000 https://cyberhyena.net/?p=239 FREE php course PHP Variables, Data Types, and Expressions Preparation #1 Learning Activity #1: declaring variable and assigning values to them In the “X:\xampp\htdocs\myphp” directory (create the “myphp” subdirectory if it does not exist), use Notepad to create a new file named lab2_1.php with the following contents: <?php $myinteger1 = 15; //declare an integer variable […]

The post free PHP programming course E3 learn to code appeared first on Cyber Hyena.

]]>
0 0
Read Time:15 Minute, 47 Second

FREE php course PHP Variables, Data Types, and Expressions Preparation #1

Learning Activity #1: declaring variable and assigning values to them

In the “X:\xampp\htdocs\myphp” directory (create the “myphp” subdirectory if it does not exist), use Notepad
to create a new file named lab2_1.php with the following contents:

<?php
$myinteger1 = 15; //declare an integer variable with value 15
$myinteger2 = -9; // negative number
echo $myinteger1 + $myinteger2 . “<br>”; //calculate the sum
$mystring1 = “An apple a day”; //declare a string with value
$mystring2 = “keeps doctors away!”;

echo $mystring1 . ” ” . $mystring2 . “<br>”; // concatenate strings
$float1 = 3.1412; //declare floating point variable with value
$float2 = 1.85e-3;
$float3 = 7.3e6;
echo $float1 * $float2 * $float3 . “<br>”; //multiplication
$first = “Nicole”; //use double quote to assign string
$last = ‘Kidman’; //use single quote to assign string
$age = 43; // numbers need no quote
echo “$first $last is $age old!” . “<br>”; //double quote will parse
echo ‘$first $last is $age old!’ . ‘<br>’; //single quote don’t parse
//use html formatting tags to format PHP outputs
echo “World <u>history</u> is <b>his</b> story, not <i>mine</i>!<br>”;

//use CSS to define style and use \ to escape sequence
echo “<div style=\”font-size:24px;color:red\”>Those who teach do not
know!</div>”;
?>

2. Test the program. The output looks:

Learning Activity #2:

In the “X:\xampp\htdocs\myphp” directory, use Notepad to create a new file named lab2_2.php with the
following contents:

<?php
$a = $b = $c = 12; // declare and assign the same values to variables
$a=$a+1; //let $a’s new value = $a’s old value (12) + 1
$b=$b-7; //let $b’s new value = $b’s old value (12) – 7
$c=$c/4; //let $c’s new value = $c’s old value (12) /4
echo “$a, $b, $c <br>”; //display new values of $a, $b, and $c
//hexadecimal and octal integers
$hex = 0xFF; // hexadecimal value
$oct = 0146; // octal value
echo “$hex – $oct <br>”;
?>

Test the program. The output looks:

13, 5, 3
255 – 102

Learning Activity #3: String variables and concatenation
1.
In the “X:\xampp\htdocs\myphp” directory, use Notepad to create a new file named lab2_3.php with the
following contents:

<?php
$word1=”for”;
$word2=”ever”;
$number1=12;
$number2=57;
// string-to-string concatenation
echo $word1 . $word2 . “<br>”;
// string-to-number concatenation (become a new string)
echo $word1 . $number1 . “<br>”;
// number-to-string concatenation (become a new string)
echo $number1 . $word1 . “<br>”;
// number-to-number concatenation (a new string?)
echo $number1 . $number2 . “<br>”;
$n = $number1 . $number2 . “<br>”;
$n = $n / 4;
echo $n; // result is 314.25, so not necessary a new string
?>

2. Test the program. The output looks:

forever
for12
12for
1257

314.25

Learning Activity #4: Understanding Quotation marks

In the “X:\xampp\htdocs\myphp” directory, use Notepad to create a new file named lab2_4.php with the
following contents:

<?php
$course = ‘CIS246’;
$semester = “Fall”;
echo ‘$course $semester<br>’;
echo “$course $semester<br>”;
echo ‘I want to take $course.<br>’;
echo “I want to take $course.<br>”;
echo ‘I won\’t see you in $semester.<br>’;
echo “I won’t see you in $semester.<br>”;
echo “<hr size=’1′ width=’100%’>”;
echo “<hr size=\”1\” width=\”100%\”>”;
?>

2. Test the program. The output looks:

Learning Activity #5: Server Variables
1.In the “X:\xampp\htdocs\myphp” directory, use Notepad to create a new file named lab2_5.php with the
following contents:

<?php
echo “<h2>I see you</h2>”;
echo “<b>Script Name</b>: “. $_SERVER[‘PHP_SELF’] . “<br>”;
echo “<b>Your Browser</b>: “. $_SERVER[‘HTTP_USER_AGENT’] . “<br>”;
echo “<b>Your IP address</b>:” . $_SERVER[‘REMOTE_ADDR’] . “<br>”;
echo “<b>Server Host Name</b>:” . $_SERVER[‘SERVER_NAME’] . “<br>”;
echo “<b>Web Server Software</b>: “. $_SERVER[‘SERVER_SOFTWARE’] . “<br>”;
echo “<b>Transmission Protocol</b>: “. $_SERVER[‘SERVER_PROTOCOL’];
?>

2. Test the program. The output looks:

Basic PHP Operators , FREE php course

Variable and operators

In order to work with strings and numbers to produce new values, your must learn PHP operators. An
operator is any symbol used to perform an operation, such as arithmetic’s operations: addition,
subtraction, multiplication, and division. The actual symbol used to perform the operation is known
as an operand.

The Assignment Operator

As introduced in the last article, the assignment operator allows you to assign a value to a variable.
You can assign strings, integers, even the results of functions. For example:

$greeting = “Good morning!”;
$number = 12;
$myfunction = dispayTime(); \\will be discussed in later lecture

The Concatenation Operator

Concatenating two strings means sticking them together, one after another, creating a new string. For
example, the string “home” concatenated with the string “town” creates the string “hometown” . In
PHP, strings can be added to each other or additional values may be added to a string using the
concatenation operator “.”. For example:

<?php
$age=21;
echo “The age is ” . $age;
?>

The output is:

The age is 21

The concatenation operator allows you to append one value to another. You can append strings, other
variables or even the results of func tions. Consider the following example,

$var = “test”;
$var2 = “This is a ” . $var;
echo $var2;

This would output:

This is a test

You can also use what’s called the Assignment Concatenation Operator ( .= )to append a new value
to the value an existing variable. For example:

$var = “An apple a day”;
$var .=” keeps doctors away.”;
echo $var;

This would output:

An apple a day keeps doctors away.

Arithmetic Operators

Just like in math, arithmetic operators in PHP are used to work with numbers. Addition, subtraction,
division, and multiplication are all supported:

Consider the following example,

<?php
$qty=15;
$price=2.71;
$amount = $qty * $price;
echo $amount;
?>

The $amount variable’s value is determined by the calculation results of $qty and $price through the
multiplication operation (*).

The resulting output is: 40.65

Incrementing/Decrementing Operators

PHP supports specific operators for incrementing (++) and decrementing (–) numbers. These provide
a short-hand way of expressing the increase or decrease of a value by the quantity one (1).
Depending on where you place the operator, it will take on a different order of operation. The table
below shows how the position of the operator affects the outcome of the variable $var.

The following example illustrates the differences:

<?php
$a = $b = $c = $d = 3;
echo $a++ . “<br>”; //increment happens after $a is read
echo ++$b . “<br>”; //increment happens before $b is read
echo $c– . “<br>”; //decrement happens after $c is read
echo –$d . “<br>”; //decrement happens before $d is read
?>

The output will be:

3
4
3
2

Increment and decrement also provides a way to perform skip counting.

Given two series A = {1, 4, 7, 10, 13} and B = {10, 8, 6, 4, 2, 0}; they both are incremented and
decremented by a number larger than 1. In such case, the increment and decrement operators are
denoted by:

+=n
-=n
where n is the increment or decrement. For example:

<?php
$x = 15; $y = 12;
$x+=5; $y-=2; //$x incremented by 5; $y decremented by 2
echo $x . “<br>”;
echo $y;
?>

The output is:
20
10

20 is the result of 15 + 5, while 10 is the result of 12 – 2.

Comparison Operators , FREE php course

There are operators like == (equals) and > (greater than) that compare two expressions, giving a
result of true or false. As the name implies, they allow you to compare two values.

Consider the following example. The date() function will retrieve the current date and time from the
server computer, the argument “H” is a format character that tells PHP to show only the hour value.

<?php
$myHour = date(“H”); // assign the hour value to $myHour variable
if ($myHour < 12) { // test the $myHour value with < operator
echo “Good morning!”;
}
elseif ($myHour < 17) {
echo “Good afternoon!”;
}
else {
echo “Good evening!”;
}
?>

Go to http://members.lycos.co.uk/cistcom/hour.php to view the sample.

Later lectures will provide a detailed discussion about how comparison operators are used in decision
making.

Logical Operators ,FREE php course

There are operators like && (AND) and || (OR) that enable you to create logical expressions that
yield true or false results. Logical operators are also called Boolean operator. They test conditions
and return tested result with logical value “FALSE” (or 0 representing false), and logical value
“TRUE” (or 1 representing true).

You can use the Truth Table below to learn how these operators work.

Do not be intimidated by these academic terms! You actually use Boolean logic in your everyday
life. For example, you just heard a lady said “My name is Jennifer AND I am a doctor”.

If the lady is actually named Megan or if she is actually a cook, then her statement would be false (the value is 0).
The statement above is actually made of two expressions or values: “My name is Jennifer” and “I am
a doctor”.

Each of those, by itself, is true or false. The “AND” in the sentence is the logical operator,
which makes one expression out of two separate expressions.

When applying them to the truth table, “My name is Jennifer” is input A, while “I am a doctor” is
input B. The entire sentence is then denoted as A AND B. If her name is Jennifer (the value is 1 –
true) but she is not a doctor (the value is 0 – false), the statement is false according to the A AND B
example form the Truth Table, which says both A and B must be true for the statement to be true.

PHP Logical Operators

FREE php course
FREE php course

For example, review the following code:

<?php
$s = 6;
$t = 5;
if ($s>4 AND $t>4) {echo “TRUE!”; }
?>

The output is 1 (indicating that the statement is “true”), because both condition $s>4 and $t>4 are
true.

You may have noticed that there are two different ways of performing a logical AND or OR in PHP.
The difference between AND and && (as well as between OR and ||) is the precedence used to
evaluate expressions. Later lectures will provide a detailed discussion about how logical operators
are used in decision making.

Bitwise operators , FREE php course

A bit is a representation of 1 or 0. Bitwise operators are used on integers. All bitwise operators

perform an operation on the one or more specified integer values as translated to binary expressions.
For example, the tilde or ~ (Bitwise NOT) operator changes binary 1s to 0s and 0s to 1s.

Consider the following example, which outputs the integer 8.

<?php
$x = 9;
$y = 10;
echo $x & $y;
?>

To understand how the bitwise operator works, it is necessary to convert all the decimal integers 8
and 9 to their binary formats. For example, the integer 9 is equivalent to 1001 in binary and the
integer 8 is equivalent to 1010 in binary.

FREE php course
FREE php course

The AND (&) bitwise operator requires bits that are set in both $x and $y must be 1’s to return 1. In
the above table, there is only one case that meets the criteria. The operation $x & $y yields a new
binary value 1000, which equals 8 in decimal format. PHP displays only the decimal results, so the
output is 8.

The OR (|) bitwise operator requires bits that are set in either $x or $y is 1 to return 1. According to
the following table, the $x | $y operation yields 1011 in binary or 11 in decimal format. The output
is 11.

FREE php course
FREE php course

The XOR (exclusive or) operator requires bits that are set in $x and $y must be different to return 1.
The $x ^ $y operation yields 11 in binary or 3 in decimal format. The output is 3.

The NOT (~) bitwise operator negates every bit in $x, meaning to turn every 1 to 0 and vice versa. $x
in binary is 1001, so ~$x is 0110. The operation ~$x & $y yields 0010, which is 2 in decimal.

The Shift Left (<<) operator shifts the bits of $x n steps to the left. For example, $x << 2 yields a
new number 100100 or 36 in decimal format.

Shift right (>>)operator shifts the bits of $x n steps to the right. For example, $x >> 2 yields a new
number 10 or 2 in decimal format.

If you are storing integer data (such as normal decimal values like the 150 and 75 mentioned earlier)
and want to perform internal translation to do binary math, use bitwise operators. Bitwise operators
are also valuable to get a NOT value which is not necessarily the exact opposite.

The Execution Operators ,FREE php course

PHP is originally created for use in a Unix environment, so it naturally supports one Unix-based
execution operator–the backquote (“). Note that these are not single-quotes. In the generic keyboard.
The backquote key looks:

~
`

Consider the following example. The statement “ls –l” is an Unix statement. If your Web server is
a Unix/Linux server, the following will display the contents of the presently working directory.

<?php
$str = `ls -al`;
echo “<pre>$str</pre>”;
?>

This operator simulates a shell prompt and executes the command as a shell command; the output
will be returned a string. This operator is functionally similar to the shell_exec() function, which
executes command via shell and return the complete output as a string. For example:

<?php
$str = shell_exec(‘ls -al’);
echo “<pre>$str</pre>”;
?>

The eval() function evaluates a string as PHP code, meaning it can convert a command-like string
into a PHP code temporarily. For example:

<?php
$x = 3.1415;
$str = “var_dump($x);”;
echo $str . “<br>”; // output the string
eval(“$str”); // run the string as PHP code
?>

The output looks:

var_dump(3.1415);
float(3.1415)

However, the string passed must be valid PHP code, including things like terminating statements
with a semicolon so the parser does not die on the line after the eval().

Type
casting in

PHP is a “loosely typed” language, meaning its variables types are determined by the values of the
variables. Although many programmers arguably believe type casting is not important to PHP, there are ways to cast types in PHP.

The var_dump() function displays information about type and value of a variable. For example:

<?php
$PI = 3.1415;
$y = true;
var_dump($x, $y);
?>

The output will be:

float(3.1415) bool(true)

Since the var_dump() function displays structured information including its type and value, it helps
to understand why PHP is loosely typed. Consider the following example. The string variable $var
is assigned two characters “1” and “2” to make new string “12”.

<?php
$var = “12”; // 12 is declared as string
echo $var + 3 . “<br>”; // 15
var_dump($var); // string(2) “12”
$var++; // increment by 1
echo $var . “<br>”; // 13
var_dump($var); // int(13)
?>

The statement $var + 3 uses an arithmetic operator to add 3 to the string “12”. In a well-structured
language such as C++ and Java, a string cannot be calculated by arithmetic operator and two
dissimilar types cannot be “added” by the addition operator. However, PHP allows such calculation
by temporarily cast the type of $var and let the value it holds determining its type. Consequently, the
output of the following statement is 15.

echo $var + 3 . “<br>”;

Such type casting is temporary, meaning it only applies to the above statement. When being tested by
the var_dump() function, as shown below, the output string(2) “12” still indicates that $var is a
string variable with two character value “12”.

var_dump($var);

The next statement $var++ forces the variable to increment by 1 and it also forces the $var variable
to cast its type to integer. Finally,

the output is

int(13) when the var_dump() function displays its
type and value.

PHP has the ability to automatically cast variable types, and this is an advantage. However, when it
comes to the time that a programmer absolutely must fix the variable to a particular type, the need to
cast variable rises.

Review Questions

1. Given the following code, what is the output?

<?php
$age=21;
echo “The age is ” . $age;
?>

A. The age is 21
B. The age is $age

C. The age is
D. “The age is ” . $age

2. Given the following code, what is the output?

<?php
$age=”12″;
$age=$age . “1”;
echo $age;
?>

A. 12.1
B. 13
C. 121
D. $age

3. Given the following code, what is the output?

<?php
$str1 = “CIS”;
$str2 = “246”;
echo $str1 . $str2;
?>

A. CIS . 246
B. CIS.246
C. CIS246
D. “CIS””246”

4. Given the following code, what is the output?
<?php
$n = 7;
$n = $n * 3;
echo $n
?>
A. 7 * 3
B. $n * 3
C. 7
D. 21
5. Given the following code, what is the output?

<?php
$x=4;
echo ++$x;
?>

A. 4
B. 5
C. ++4
D. ++$x

6. Given the following code, what is the output?

<?php
$y = 15;
echo $y+=5;

?>

A. 15
B. 10
C. 20
D. $y+=5

7. Given the following code, what is the output?

<?php
$x = 9;
$y = 10;
echo ($x | $y);
?>

A. 11
B. 9
C. 8
D. 2

8. Given the following code, what is the output?

<?php
$x = 9;
echo ($x << 2);
?>

A. 18
B. 29
C. 36
D. 27

9. Given the following code, what is the output?

<?php
$x = 256;
$x = (string) $x;
var_dump($x);
?>

A. string “256”
B. string(“256”)(3)
C. string(3) “256”
D. string(“256”)

10. Which increments a variable $m by 4?

A. $m=$m++4;
B. $m+=4;
C. $m=+4;
D. $m++4;

YOU CAN FIND ALL COURSE LECTURES HERE 

FREE php course

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

The post free PHP programming course E3 learn to code appeared first on Cyber Hyena.

]]>
https://cyberhyena.net/blog/2021/03/12/free-php-programming-course-e3-learn-to-code/feed/ 0
free PHP programming course E2 learn to code https://cyberhyena.net/blog/2021/03/12/free-php-programming-course-e2-learn-to-code/ https://cyberhyena.net/blog/2021/03/12/free-php-programming-course-e2-learn-to-code/#respond Fri, 12 Mar 2021 20:47:34 +0000 https://cyberhyena.net/?p=209 FREE php course Preparation #1: Build a testing Web Server 1. Use Internet Explorer to visit http://www.apachefriends.org/en/xampp-windows.html and download the latest installer of XAMPP for Windows. As of the time this lecture is written, the latest version is 1.8.0. 2. Launch the installer file (e.g. xampp-win32-1.8.0-VC9-installer.exe) read more about how to install xampp here  Learning […]

The post free PHP programming course E2 learn to code appeared first on Cyber Hyena.

]]>
0 0
Read Time:15 Minute, 0 Second

FREE php course Preparation #1: Build a testing Web Server
1. Use Internet Explorer to visit http://www.apachefriends.org/en/xampp-windows.html and download the
latest installer of XAMPP for Windows. As of the time this lecture is written, the latest version is 1.8.0.
2. Launch the installer file (e.g. xampp-win32-1.8.0-VC9-installer.exe)

read more about how to install xampp here 

Learning Activity #3: Basic PHP Start and End tags
1.
In the “X:\xampp\htdocs\myphp” directory, use Notepad to create a new file named lab1_3.php with the
following contents:

<html>
<?php echo “Display the word ‘Welcome’ using ‘&lt;?php … &gt;’!”; ?><br>
<? echo “Display the word ‘Welcome’ using ‘&lt;? … &gt;’!”; ?><br>
<script language=”php”> echo “Display the word ‘Welcome’ using ‘&lt;script&gt;’!”;
</script>
</html>

2. Use a Web browser to visit http://localhost/myphp/lab1_3.php, you should see the following window.

 

Learning Activity #4: Commenting your PHP code FREE php course

1.
In the “X:\xampp\htdocs\myphp” directory, use Notepad to create a new file named lab1_4.php with the
following contents:

<html>
<body>
<!– This line is an HTML comment –>
<?php
//This line is a single line PHP comment.
/*This is a multiple-line comment. Line 1
Line 2
Line 3 */
# This line is a Linux/Unix shell comment
echo “Do you see any of the comment?”;
?>
</body>
</html>

 

2. Use a Web browser to visit http://localhost/myphp/lab1_3.php, you should see the following window.

 

Learning Activity #5: Using HTML tag to format PHP output FREE php course

1.
In the “X:\xampp\htdocs\myphp” directory, use Notepad to create a new file named lab1_5.php with the
following contents:

<html>
<body bgcolor=”yellow”>
<b><?php echo “PHP Programming!” ?></b><br>
<u><?php echo “PHP Programming!” ?></u><br>
<i><?php echo “PHP Programming!” ?></i><br>
<s><?php echo “PHP Programming!” ?></s><br>
<h1><?php echo “PHP Programming!” ?></h1><br>
<pre><?php echo “PHP Programming!” ?></pre><br>
<center><?php echo “PHP Programming!” ?></center><br>
</body></html>

 

Use a Web browser to visit http://localhost/myphp/lab1_3.php, you should see the following window.

 

FREE php course
FREE php course

Lecture #2: PHP Variables, Data Types, and Expressions

Definition of data type

Human languages, such as English, use combinations of character to represent data. In English,
characters include alpha characters (lowercase and uppercase), numerals (0, 1, 2, .., 9), and symbols
($,#,*,&..). For example:
• Jennifer represents a girl’s first name, and it is a combination of alphabets.
• 714-852-9634 is a phone number, and it is a combination of numerals and symbol (-).
• D009865471 is a student ID, and it is a combination of alphabet and numerals
Different data can use different combinations of alpha characters, numerals, and symbols; therefore,
a data type is set of data with values having predefined characteristics and format. A data type is a
specification that assures the use of a specific set of values.
Usually a limited number of data types are built into a programming language. The language usually
specifies the range of values for a given data type, how the computer processes the values, and how
they are stored. In other words, the data type defines how computers should process a given variable
( of that data type).

 

What is a variable?

In programming languages, a variable is a language object that may hold different values for a period
of time. The value of a variable is usually restricted to a certain data type, such as an integer or
floating-point number.

A variable can be thought of as a programming construct used to store both numeric and non-
numeric data.In some cases, the contents of a variable can be changed during program execution. A
variable needs a name to be used to represent a data item whose value can be changed while the
program is running.

Variables in PHP are represented by the dollar sign prefix followed by the name of the variable. The
variable name is case-sensitive. For example:

$name;
$num;

Usually, the value of a given variable is provided by the user. For example, you enter your age to the
text box and then click Go. Your age will be assigned to a variable as value and is later retrieved and
inserted to the next sentence. You can keep on entering different numbers. See the example PHP
code below.

<?php
$age = $_POST[“age”];
?>

…….
<form action=”test.php” method=”post”>
<input type=”text” name=”age”>
…….

The above PHP example declares a variable with a valid name (e.g., $age) without assigning initial
value (meaning it has a null value). The “$age = $_POST[“age”];” line will accept whatever
value the user assigns to the $age through a form. When the user enters a value (e.g., 19), the user
indeed assigns a value to the variable dynamically.

PHP Expressions

PHP expressions are the building blocks of a PHP code. In PHP, almost any code you write is an
expression. The PHP manual defines a PHP expression as “anything that has a value”.

The most basic forms of expressions are constants and variables. When you type $a = 5, you assign

“5” to the variable, $a. In other words $a = 5 is an expression that the variable $a has the value of 5.
After this assignment, if you wrote $b = $a, you technically express your wish of $b = 5.

Some expressions can be considered as statements. In this case, a statement has the form of
expression;

namely, an expression followed by a semicolon. The following example is a expression and a valid
PHP statement.

$b = $a = 5;

Given an expression, $a = 5. There are two objects involved, the value of the integer 5 and the
variable $a which is being assigned with 5. It simply means that $a = 5. Regardless of what it does, it
is an expression that $a is given the value 5. Thus, writing something like “$b = $a = 5;” or “$b
= ($a = 5);” is equivalent to writing two statements: “$a = 5;” and “$b = 5;” (a semicolon
marks the end of a statement). Since assignments are parsed in a right to left order, you need to write
$b = $a = 5;    (or “$a = $b = 5;”).

Concept of using escaped sequence

PHP reserves many characters to help processing values held by variables, such as single quote (‘),
double quote (‘), dollar sign ($), and others. In other words, such reserved characters are not treated
as string literals as in plain English.

Sometimes it is necessary to display special PHP reserved characters as text. In this case, you will
then need to escape the character with a backslash (\). PHP uses the backslash (\) character to
restore and/or redefine characters that otherwise have a special PHP meaning, such as the newline
backslash itself (\n), or the quote character. The restoration/redefinition is known as a “escape
sequence “.

In many languages, escape sequences are used to format values of variables.

 

For example, review the following PHP code:

<?php
echo “A newline starts here \n”;
echo “A carriage return is \r”;
echo “A tab is \t.”;
echo “A dollar sign is \$”;
echo “A double-quote is \””;
?>

The output should be:

A newline starts here
A carriage return is
A tab is
.A dollar sign is $A double-quote is ”

Important Note!

There is a critical problem with using an escaped sequence with web browser–the web browser will
simply ignores blank spaces. And that explains why you did not get the above results when you test
them with web browser. You can use the “View Source” function of the browser to view the correct
output.

Basic PHP data types

PHP supports a number of different data types. The common ones are integers, floating point
numbers, strings, and arrays. In many languages, it’s essential to specify the variable type before
using it.

For example, a variable may need to be specified as type integer or type array. A list of
some of the PHP data types and their definitions are:

• integer: An integer is a plain whole number like 35, -80, 1527 or 1. They cannot have fractional
part.
• floating-point: A floating-point number is typically a fractional number such as 18.5 or
3.141592653589. Floating point numbers may be specified using either decimal or scientific
notation.
• string: A string is a sequence of characters, like “hello world” or “abracadabra”. String values
may be enclosed in either double quotes (“ and ”) or single quotes(‘ and ’). A blank space inside
the quotes is also considered a character.
• boolean: A Boolean variable simply specifies a true or false value.
• array: An array is a collection of items that have something in common. A detailed discussion is
given in a later lecture.

Variables in PHP are represented by a dollar sign ($) followed by the name of the variable. For
example, $popeye, $one and $INCOME are all valid PHP variable names. The variable name is
case-sensitive.

To assign a value to a variable, you use the assignment operator, the “=” sign. For example, review
the following PHP code:

<?php
$myvar = “Jennifer”;
$Myvar = “Lopez”;
echo “$Myvar, $myvar”;
?>

The output will be:
Lopez, Jennifer

Both $myvar and $Myvar represent two different variables. The “=” sign is the assignment sign.
$myvar is assigned a value “Jennifer”, while $Myvar is assigned another value “Lopez”.

The echo command displays both values to the screen. The value being assigned need not always be fixed; it
could also be another variable, an expression, or even an expression involving other variables.

For example:

<?php
$dog_age=10;
$human_age = $dog_age * 7;
echo “Your dog is $human_age years old in human age.”;
?>

A variable $dog_age is declared and assigned a value 10. The value of $dog_age variable is then
multiplied by 7, giving a value of 70, as the value of the $human_age variable.

The echo command display the value of $human_age, and the output will be:

Your dog is 70 years old in human age.

Interestingly enough, you can also perform more than one assignment at a time

. Consider the following example, which simultaneously assigns three variables to the same value:

<?php
$price1 = $price2 = $price = 15;
?>

Boolean

Boolean variables are commonly used for decision making. For example:

<?php
if ($add_line == TRUE) {
echo “<hr>”;
}
?>

Note: The above example uses if..then statement for decision making. A detailed discussion about
how to use decisive logic is given in later lecture.

Integers

In PHP, integers can be based in decimal (10-based), hexadecimal (16-based) ,or octal (8-based)
notation, optionally preceded by a sign (- or +).

Important concept:

• Decimal numbers have numerals 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
• Octal numbers have numerals 0, 1, 2, 3, 4, 5, 6, and 7.
• Hexadecimal numbers have numerals 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.

To define the base of a number, use the following rules:

• if the default base is decimal, there is no need to precede the number with anything.
• to use the octal notation, you must precede the number with a 0 (zero).
• to use hexadecimal notation precede the number with 0x (zeroX).

To specify a positive or negative value, use the following rules:

• numbers are positive by default.
• to specify the negative value, precede the number with a negative “-” sign.
For example,

<?php
$myNo1 = 5678; // decimal number
$myNo2 = -5678; // a negative number
$myNo3 = 0123; // octal number (equivalent to 83 decimal)
$myNo4 = 0x1A; // hexadecimal number (equivalent to 26 decimal)
echo “$myNo1, $myNo2, $myNo3, $myNo4”;
?>

FREE php course ,Floating point numbers

Floating point numbers (also known as “floats”, “doubles” or “real numbers”) can be specified using
any of the following syntax:
Math format. Simply show the integer and the decimal fractions, such as 3.14125.
Scientific format. In scientific format, the natural logarithm (e) is used to denote the exponent.
For example, 6.25X1015 is expressed as 6.25+e15 (or simply 6.25e15), while 2.74X10-23 is 2.74-
e23. The natural logarithm letter distinction (e) is not case sensitive. You can use “e” or “E” to
express scientific formatted numbers.

 

Consider the following example:

<?php
$a = 3.125;
$b = 1.2e3;
$c = 5.27E-10;
echo “$a <br>”;
echo “$b <br>”;
echo “$c <br>”;
?>

The output should look like this:

3.125
1200
5.27E-10

 

Strings

A string is series of characters. A string literal can be specified in two different ways.

• Single quoted. The easiest way to specify a simple string is to enclose it in single quotes (the
character ‘). But, if you use single quotes (‘) for your string, all characters are printed as-is.
• Double quoted. In PHP, escape sequences only work with double quotes (“).
Consider the following example with double quotes,

<?php
echo “Line 1\nLine 2”;
?>

The output should be:

Line 1
Line 2

However, when using single quotes,

<?php
echo ‘Line 1\nLine 2’;
?>

the output should change to (however, the \n is ignored by web browser):

Line 1\nLine 2

The most important difference between the two is that a string enclosed in double quotes is parsed
by PHP.

This means that any variable in it will be expanded.

<?php
$var = ‘apple<br>’;
echo “$var”; // Results in the value of $var being printed
echo ‘$var’; // Results in the word ‘$var’
?>

The output is then:

apple
$var

PHP Variable

There are a few rules that you need to follow when choosing a name for your PHP variables.
• PHP variables must start with a letter – an alpha charater.

Naming Conventions

• PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-
9, or _ .
• Variables with more than one word should separate each word with an underscore character
( _ ). For example, $my_variable .
Do not use keywords and reserved words to name variable. They have special meaning in PHP.
Some keywords and reserved words represent functions, constants, or other PHP features.

According to PHP manual (http://us3.php.net/manual/en), $this is a special variable name that
cannot be assigned.

FREE php course , Predefined variables

PHP provides a large number of predefined variables. They are a preferred method for retrieving
external variables. PHP itself creates some of the variables, while many of the other variables change
depending on which operating system and Web server PHP is running. Rather than attempt to
compile a complete listing of available predefined variables, you can run the following script to
display all of the available variables.

<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>

The following example will display the filename of the currently executing script, the type of web
browser or user agent that is being used to access the current script, the server’s IP address, the
server’s host name, and so on.

<?php
echo $_SERVER[‘PHP_SELF’] . “<br>”;
echo $_SERVER[‘HTTP_USER_AGENT’] . “<br>”;
echo $_SERVER[‘REMOTE_ADDR’] . “<br>”;
echo $_SERVER[‘REQUEST_METHOD’] . “<br>”;
echo $_SERVER[‘SERVER_NAME’] . “<br>”;
echo $_SERVER[‘SERVER_SOFTWARE’] . “<br>”;
echo $_SERVER[‘SERVER_PROTOCOL’];
?>

You can use the following common predefined variable to retrieve information.

 

To view a comprehensive list of Web server, environment, and PHP variables offered on your
particular system setup, simply visits the demo site
at:http://us3.php.net/manual/en/reserved.variables.server.php.

 

Review Questions

1. Which escape sequence is equivalent to the [Tab] key?

A. \tab
B. /tab
C. \t
D. /t

2. Given the following code, what is the output?

<?php
$x = $y = 2;
echo ($y);
?>

A. 11
B. 9
C. 8
D. 2

3. Which is a string?

$a = “Hello, world!”;
$b = “1 2/5”;
$c = “02.23.72”;

A. $a
B. $b
C. $c

D. All of the above

4. Which is a floating-point variable?

$a = 12;
$b = 972;
$c = 15.48;
$d = -43;

A. $a
B. $b

C. $c
D. $d

5. In the following code, $larger is a __ variable.

<?php $larger = TRUE; ?>

A. Comparison
B. Boolean
C. Floating-point
D. Logical

6. The output of the following code is __.

<?php echo 0x1A; ?>

A. 25
B. 26
C. 81
D. 83

7. The output of the following code is __.

<?php
$x = 5;
$z = $y = $x;
echo $z;
?>

A. 5
B. $y
C. $y = $x
D. an error message

8. The output of the following code is __.

<?php
$y = ($x = 7);
echo $y;
?>

A. ($x = 7)
B. 7
C. $x = 7
D. $x

9. Which is a floating-point variable?

<?php
$a = 3.125;
$b = 1.2e3;
$c = 5.27E-10;
?>

A. $a
B. $b
C. $c
D. All of the above

10. Which is a possible output of the following code?

<?php echo $_SERVER[‘SERVER_NAME’]; ?>

A. CISDEpt.com
B. 207.125.11.110
C. SNMP
D. /usr/cis246/test.php

FIND ALL COURSE LECTURES ON THIS LINK 

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

The post free PHP programming course E2 learn to code appeared first on Cyber Hyena.

]]>
https://cyberhyena.net/blog/2021/03/12/free-php-programming-course-e2-learn-to-code/feed/ 0