1. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Introduction to PHP (Hypertext Preprocessor)
PHP Tags:
When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop
interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different
documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the
text through echo or print.
<?php if ($expression == true){ ?>
This will show if the expression is true.
<?php } else { ?>
Otherwise this will show.
<?php } ?>
PHP Comments:
<?php
echo 'This is a test'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>
PHP Datatypes:
Boolean (TRUE/FALSE) – case insensitive
False – FALSE, 0, -0, 0.0, -0.0, “”, “0”, array with zero elements, NULL (including unset variables)
True – Every other value including NAN
Integer
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
0 = False, Null
1 = True
2. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Floating Point Numbers
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Strings (Single quoted/ Double quoted)
<?php
echo 'this is a simple string';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I'll be back"';
// Outputs: You deleted C:*.*?
echo 'You deleted C:*.*?';
// Outputs: This will not expand: n a newline
echo 'This will not expand: n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
<?php
$juice = "apple";
echo "He drank some $juice juice.";
?>
<?php
$str = 'abc';
var_dump($str[1]);
var_dump(isset($str[1]));
?>
. (DOT) – to concat strings
“1” – True
“” – False/ Null
Array
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
$array1 = array("foo", "bar", "hello", "world");
var_dump($array1);
?>
3. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
<?php
$arr = array(5 => 1, 12 => 2);
$arr[13] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
PHP Variables:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-
sensitive.
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
4. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Predefined Variables:
$GLOBALS – References all variables available in global scope
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "n";
echo '$foo in current scope: ' . $foo . "n";
}
$foo = "Example content";
test();
?>
$_SERVER – server and execution environment information
<?php
$indicesServer = array(
'PHP_SELF',
'SERVER_ADDR',
'SERVER_NAME',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'REQUEST_TIME',
'QUERY_STRING',
'DOCUMENT_ROOT',
'HTTPS',
'REMOTE_ADDR',
'REMOTE_HOST',
'REMOTE_PORT',
'REMOTE_USER',
'SERVER_PORT',
'SCRIPT_NAME',
'REQUEST_URI') ;
echo '<table style=”width:100%;”>' ;
foreach ($indicesServer as $arg) {
if (isset($_SERVER[$arg])) {
echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ;
}
else {
echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ;
}
}
echo '</table>' ;
?>
$_GET – an associative array of variables passed to the current script via the URL parameters
$_POST – an associative array of variables passed to the current script via the HTTP POST method when using
application/x-www-form-urlencoded or, multipart/form-data as the HTTP
$_FILES – an associative array of items uploaded to the current script via the HTTP POST method
$_REQUEST -- An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$_SESSION -- An associative array containing session variables available to the current script.
$_COOKIE -- An associative array of variables passed to the current script via HTTP Cookies.
5. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Operators and Operator Precedence:
visit here https://www.php.net/manual/en/language.operators.php
Control Structures:
if-elseif-else statement
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
while loop
<?php
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
?>
do-while loop
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
for loop
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
foreach loop
<?php
$a = array(1, 2, 3, 17);
$i = 0;
foreach ($a as $v) {
echo "$a[$i] => $v.n";
$i++;
}
$a = array(
"one" => 1,
"two" => 2,
6. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "$a[$k] => $v.n";
}
//multi-dimensional array
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2n";
}
}
?>
break, continue, switch, return
similar as before
include/require
The include/require statement includes and evaluates the specified file. The include construct will emit a warning if it
cannot find a file; this is different behavior from require, which will emit a fatal error.
within vars.php file
<?php
$color = 'green';
$fruit = 'apple';
?>
within test.php file
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
include_once / require_once
The include_once statement includes and evaluates the specified file during the execution of the script. This is a
behavior similar to the include statement, with the only difference being that if the code from a file has already been
included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included
just once.
<?php
var_dump(include_once 'fakefile.ext'); // bool(false)
var_dump(include_once 'fakefile.ext'); // bool(true)
?>
7. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Functions:
<?php
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.n";
}
?>
<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.n";
}
}
/* We can't call bar() yet
since it doesn't exist. */
foo();
/* Now we can call bar(),
foo()'s processing has
made it accessible. */
bar();
?>
///anonymous functions in PHP
<?php
$greet = function($name)
{
printf("Hello %srn", $name);
};
$greet('World');
$greet('PHP');
?>
8. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Some Functions:
Variable Handling
Functions
empty($var) -- Determine whether a variable is empty i.e. it doesn’t exist or value equals FALSE.
isset($var) -- Determine if a variable is declared and value is different than NULL
unset($var) -- Unset a given variable or, destroys a variable
print_r ($var) -- Prints human-readable information about a variable
var_dump($var) -- Dumps information about a variable
Array Functions count($a) -- Count all elements in an array
array_key_exists('first', $search_array) -- Checks if the given key or index exists in the array
array_keys($array) -- Return all the keys of an array
array_values($array) -- Return all the values of an array
array_push($stack, "apple", "raspberry") -- Push one or more elements onto the end of array
array_pop($stack) -- Pop the element off the end of array
array_unshift($queue, "apple", "raspberry") -- Prepend one or more elements to the beginning
of an array
array_shift($stack) -- Shift an element off the beginning of array
array_search('green', $array) -- Searches the array for a given value and returns the first
corresponding key if successful
array_slice($input, 0, 3) -- Extract a slice of the array
array_splice($input, -1, 1, array("black", "maroon")) -- Remove a portion of the array and
replace it with something else
sort($array), rsort($array), ksort($array), krsort($array)
String Functions strlen(‘abcd’) -- Get string length
echo "Hello World" -- Output one or more strings
explode(" ", $pizza) -- split a string by a string
implode(",", $array) -- Join array elements with a string
htmlentities("A 'quote' is <b>bold</b>") -- Convert all applicable characters to HTML entities
html_entity_decode(“I'll "walk" the <b>dog</b>”) -- Convert HTML
entities to their corresponding characters
htmlspecialchars($str) — Convert special characters to HTML entities
htmlspecialchars_decode($encodedstr) — Convert special HTML entities back to characters
md5($password) – calculate the md5 hashing of user string
sha1($password) – calculate the sha1 hashing of user string
parse_str($str,$output_array) -- Parses the string into variables
example:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
// Recommended
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz