0% found this document useful (0 votes)
32 views

Chapter 1 & 2 Introduction To PHP

Uploaded by

abaasmuuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Chapter 1 & 2 Introduction To PHP

Uploaded by

abaasmuuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Chapter 1 Introduction to PHP

PHP borrows a bit of its syntax from other languages such as C and Java. It is really a
hybrid language, taking the best features from other languages and creating an easy-to-
use and powerful scripting language.
When you finish reading this chapter, you will have learned
1. The basic language structure of PHP
2. How PHP is embedded in HTML
3. How to write comments
4. Managing variables and basic data types
5. Defining constants for simple values
6. The most common operators in php
7. Built-in or user-defined functions

First program
Note that PHP pages are mixtures of three things, namely text, HTML code, and PHP
script. Pages containing PHP script are different from pages that contain only HTML, and
in order to identify them to the PHP engine, they are saved with the .php suffix.
Open Notepad and write the following code:

<HTML>
<HEAD>
<TITLE>Home</TITLE>
</HEAD>
<BODY>
This page will print the following text:<br>
<?php
echo "HELLO WORLD!!! ";
?>
</BODY>
</HTML>

1
Save this as Index.php, change Save as type to All Files, in the root directory (C:\wamp\
www\Jarane) of your web server.
The word localhost is used in URLs to specify the local computer, which will also
respond to the IP address of 127.0.0.1, so you can use either method of calling up the
document root of your web server.
Next, ensure that the server is running and type in the full URL of your web server and
web page, mine would be http://localhost/Jarane/Index.php (you can omit file name as
file name is index.php).

In the HTML part, you can use all html tag and attributes as usual. Also, in the PHP part
you can embed html tags and attributes to the echo statement but ensure to use single
quotations with the attributes. The PHP part starts with <?php and ends with ?> and all
PHP codes in between.

In this example, you see that your PHP code sits embedded in your HTML. Every time
the PHP interpreter reaches a PHP open tag <?php it runs the enclosed code up to the
delimiting ?> marker. PHP then replaces that PHP code with its output (if there is any)
while any non-PHP text (such as HTML) is passed through as-is to the web client.

How to Insert Comments in PHP


You can write comments three different ways:
Multi-line comment
/* This is a C like comment
which can span multiple
lines until the closing tags
*/
Single line comment
// This is a C++ like comment which ends at the end of the line

You can also write single line comment by using # symbol

2
# This is a shell like comment which ends at the end of the line

Variables
Variables in PHP are quite different from compiled languages such as C and Java. You
do not need to declare variables before using them, you do not need to declare their type
and, as a result, a variable can change the type of its value as much as you want.
Variables in PHP are preceded with a $ sign, and similar to most modern languages, they
can start with a letter (A-Z or a-z) or _(underscore) and can then contain as many
alphanumeric characters and underscores as you like.
Examples of legal variable names include:
$count
$_Obj
$A123
Example of illegal variable names include:
$123
$*ABC
The following code example uses variables:
$PI = 3.14;
$radius = 5;
$circumference = $PI * 2 * $radius;
You can see that none of the variables are declared before they are used. Also, the fact
that $PI is a floating-point number, and $radius (an integer) is not declared before they
are initialized.

PHP Case Sensitivity


In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.

3
Basic Data Types
Five different data types exist in PHP. The previously discussed variables can contain
values of any of these data types without explicitly declaring their type. The variable
“behaves” according to the data type it contains.
Integers
Integers are whole numbers and are equivalent in range as your C compiler’s long value.
Integers can be written in decimal, hexadecimal (prefixed with 0x), and octal notation
(prefixed with 0), and can include +/- signs.
Some examples of integers include
240000
0xABCD
007
-100

Floating-Point Numbers
Floating-point numbers (also known as real numbers) represent real numbers and are
equivalent to your platform C compiler’s double data type. On common platforms, the
data type size is 8 bytes. Floating-point numbers include a decimal point and can include
a +/- sign and an exponent value.
Examples of floating-point numbers include
3.14
+0.9e-2
54.6E42

Strings
Strings in PHP are a sequence of characters that are always internally null terminated.
However, unlike some other languages, such as C, PHP does not rely on the terminating
null to calculate a string’s length, but remembers its length internally.
When writing string values in your source code, you can use double quotes ( " ) or single
quotes ( ' ).

4
Booleans
A Boolean value can be either true or false. PHP automatically converts types when
needed. Boolean is probably the type that other types are most often converted to behind
the scenes. This is because, in any conditional code such as if statements, loops, and so
on, types are converted to this scalar type to check if the condition is satisfied. Also,
comparison operators result in a Boolean value.
Consider the following code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator = = 0) {
echo "The denominator needs to be a non-zero number";
}

The result of the equal operator is a Boolean; in this case, it would be false and, therefore,
the if ( ) statement would not be entered.
Now, consider the next code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator) {
echo "One over four";
}
else
{
echo "The denominator needs to be a non-zero number";
}

You can see that no comparison operator was used in this example; however, PHP
automatically internally converted $denominator or, to be more accurate, the value 5 to
its Boolean equivalent, true, to perform the if ( ) statement and, therefore, prints the
message "One over four".

Although not all types have been covered yet, the following table shows truth values for
their values. You can revisit this table to check for the types of Boolean value
equivalents, as you learn about the remaining types.
5
Null
Null is a data type with only one possible value: the NULL value. It marks variables as
being empty, and it is especially useful to differentiate between the empty string and null
values of databases.
The isset ($variable) returns false for NULL, and true for any other data type, as long as
the variable you are testing exists.
The following is an example of using NULL:
$value = NULL;

Constants
In PHP, you can define names, called constants, for simple values. As the name implies,
you cannot change these constants once they represent a certain value. The names for
constants have the same rules as PHP variables except that they do not have the leading
dollar sign. It is common practice in many programming languages—including PHP—to
use uppercase letters for constant names, although you do not have to. If you wish, which
we do not recommend, you may define your constants as case-insensitive, thus not
requiring code to use the correct casing when referring to your constants.

To define a constant, use the following function:

define("CONSTANT_NAME", value [, case_sensitivity])

Where:
 "CONSTANT_NAME" is a string.
 value is any valid PHP expression excluding arrays and objects.
 case_sensitivity is a Boolean (true/false) and is optional. The default is true (0).

An example for a built-in constant is the Boolean value true, which is registered as case-
insensitive.
Here is a simple example for defining and using a constant:
6
define("MY_OK", 0);
define("MY_ERROR", 1);
echo ("MY_ERROR");
echo ("MY_OK");

OPERATORS
PHP contains three types of operators: unary operators, binary operators, and one ternary
operator.

Binary operators are used on two operands:


2+3
14 * 3.14
$i – 1

Binary Operators
Arithmetic Operators: All the binary operators (except for the concatenation operator)
work only on numeric operands. If one or both of the operands are strings, Booleans, or
nulls, they are automatically converted to their numeric equivalents before the calculation
is performed (according to the previous table).

Operator Name Value


+ Addition The sum of the two operands.
- Subtraction The difference between the two operands.
* Multiplication The product of the two operands.
/ Division The quotient of the two operands.
% Modulus The result is the remainder of the division of the first
operand by the second operand.

Concatenation Operator (.)

7
The concatenation operator concatenates two strings. This operator works only on
strings; thus, any non-string operand is first converted to string.
The following example would print out "The year is 2010":

$year = 2000;
echo "The year is ". $year;

The integer $year is internally converted to the string "2000" before it is concatenated
with the string’s prefix, "The year is".

Assignment operator ( = ): enable you to write a value to a variable. The first operand
(the one on the left of the assignment operator) must be a variable. The value of an
assignment is the final value assigned to the variable; for example, the expression: $var =
5 has the value 5 (and assigns 5 to $var).

Comparison Operators
Comparison operators enable you to determine the relationship between two operands.
The comparison results in a Boolean value.
For the following comparison operators, automatic type conversions are performed, if
necessary.
Operator Name Value
== Equal to Checks for equality between two arguments
performing type conversion when necessary:
1= =”1” results in true
1= =1 results in true
!= Not equal to Inverse of = =.
> Greater than Checks if first operand is greater than second.
< Smaller than Checks if first operand is smaller than second.
>= Greater than or equal to Checks if first operand is greater or equal to
second.
<= Smaller than or equal to Checks if first operand is smaller or equal to
8
second.

Logical Operators
Logical operators first convert their operands to Boolean values and then perform the
respective comparison.
Operator Name Value
&&, and Logical AND The result of the logical
AND operation between
the two operands
||, or Logical OR The result of the logical
OR operation between the
two operands

Unary Operators
Unary operators act on one operand.
Negation Operators
Negation operators appear before their operand—for example, !$var (! is the operator,
$var is the operand).

Increment/Decrement Operators
Increment/decrement operators are unique in the sense that they operate only on
variables and not on any value. The reason for this is that in addition to calculating the
result value, the value of the variable itself changes as well.

Operator Name Effect on $var Value of the Expression


$var++ Post-increment $var is incremented by 1. The previous value of
$var.

++$var Pre-increment $var is incremented by 1. The new value of $var

9
(incremented by 1).
$var-- Post-decrement $var is decremented by 1. The previous value of
$var.
--$var Pre-decrement $var is decremented by 1. The new value of $var
(decremented by 1).

As you can see from the previous table, there is a difference in the value of post- and pre-
increment. However, in both cases, $var is incremented by 1. The only difference is in
the value to which the increment expression evaluates.
Example 1:
$num1 = 5;
$num2 = $num1++; // post-increment, $num2 is assigned $num1's original value
echo $num1; // this will print the value of $num1, which is now 6
echo $num2; // this will print the value of $num2, which is the original value of
$num1, thus, 5

Example 2:
$num1 = 5;
$num2 = ++$num1; // pre-increment, $num2 is assigned $num1's incremented
value (6)
echo $num1; // this will print the value of $num1, which is now 6
echo $num2; // this will print the value of $num2, which is the same as the value
of $num1, thus, 6
The same rules apply to pre- and post-decrement.

The One and Only Ternary Operator


One of the most elegant operators is the ? : (question mark) operator. Its format is:
truth_expr ? expr1 : expr2
The operator evaluates truth_expr and checks whether it is true. If it is, the value of the
expression evaluates to the value of expr1 (expr2 is not evaluated).
If it is false, the value of the expression evaluates to the value of expr2 (expr1 is not
evaluated).

10
For example, the following code checks whether $a is greater than or equal 50 and
displays a message accordingly:
<?php
$a = 79;
$message = ($a >= 50) ? "$a is pass" : "$a is fail";
echo $message;
?>
This example prints the following message: 79 is pass.

11

You might also like