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 %
Previous post free PHP programming course E2 learn to code
FREE php course Next post free PHP programming course E4 learn to code

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

Close