The Basic PHP - Chapter 1
The Basic PHP - Chapter 1
What is PHP? History of PHP Why PHP ? What is PHP file? What you need to start using PHP ? Syntax PHP code . echo & print Statement Variables. Data Types. Constants &Operators. Conditional Statements & Loops.
What is PHP?
Personal Homepage Tools/Form Interpreter PHP is a Server-side Scripting Language designed specifically for the Web.
History of PHP
PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix.
PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc.
PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans .
PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added.
PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP
Why PHP ?
etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
Structurally similar to C/C++ Supports procedural and object-oriented paradigm (to some degree)
PHP can create, open, read, write, and close files on the server
PHP can collect form data PHP can send and receive cookies PHP can add, delete, modify data in your database PHP can restrict users to access some pages on your website PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML
PHP files can contain text, HTML, JavaScript code, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain HTML
Installation
1.
2.
3.
4.
5.
6.
A PHP script can be placed anywhere in the document. A PHP script starts with
ASP Style:
<% echo Hello World!; %>
Echo
parameters passed to it .
The typical usage for this is to send data to the clients web-browser
Syntax : void echo (string arg1 [, string argn...]) In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function
Echo - Example
<?php
echo This my first statement in PHP language;
?>
print is not actually a real function (it is a language construct) so you are not required to
Echo Vs Print
Improve this chart Parameters: Echo echo can take more than one Print print only takes one parameter.
echo does not return any value void echo ( string $arg1 [, string $... ] )
What is it?:
Variables
expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, carname, totalvolume).
Rules for PHP variables: A variable starts with the $ sign, followed by the name of the variable
Variables
A variable name should not contain spaces Variable names are case sensitive ($y and $Y are two different variables)
Variables
echo( $name);
?>
After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable xwill hold the value 5.
Note: When you assign a text value to a variable, put quotes around
the value.
Variables
<?php
$name = ali; $age = 23;
?>
In the example above, notice that we did not have to tell PHP which
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, we will have to declare (define) the type and name of the variable before using it.
Variables
<?php $name = 'elijah'; $yearborn = 1975; $currentyear = 2005; $age = $currentyear - $yearborn; echo ("$name is $age years old."); ?>
Variables
<?php $name = Ali"; // declaration ?>
<html>
<head> <title>A simple PHP document</title> </head> <body style = "font-size: 2em">
<p> <strong>
<!-- print variable names value --> Welcome to PHP, <?php echo( "$name" ); ?>!
</strong> </p>
</body> </html>
The scope of a variable is the part of the script where the variable
can be referenced/used.
After we have created a string variable we can manipulate it. A string can be
used directly in a function or it can be stored in a variable.
In the example below, we create a string variable called txt, then we assign the text "Hello world!" to it. Then we write the value of the txt variable to the output:
<?php
$txt="Hello world!"; echo $txt; ?>
Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed).
Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you what to echo "The $types are" That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such.
Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax.
Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings.
The difference is that not even single quotes or backslashes have to be escaped. A
nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.
Heredoc
<?php $name='MyName'; echo <<<EOT My name is "$name". I am printing some A Now, I am printing some {A}. This should print a capital 'A': \x41 EOT; ?>
My name is "MyName". I am printing some A Now, I am printing some {A}. This should print a capital 'A': A
Nowdoc
<?php $name='MyName'; echo <<<'EOT' My name is "$name". I am printing some A Now, I am printing some {A}. This should print a capital 'A': \x41 EOT; ?>
My name is "$name". I am printing some A Now, I am printing some {A}. This should print a capital 'A': \x41
?>
<?php
$word = World;
?>
Comments in PHP
Whitespace
The concatenation operator (.) is used to join two string values together.
The example below shows how to concatenate two string variables together:
<?php $txt1="Hello!"; $txt2=" world !"; echo $txt1 . " " . $txt2; // Hello world ! ?>
$string3=$string1 . . $string2;
Print $string3; ?>
Hello PHP
Example
<?php
$foo = 25;
// Numerical variable
$bar = Hello; // String variable echo $bar; echo $foo,$bar; // Outputs Hello // Outputs 25Hello
echo 5x5=,$foo;
echo 5x5=$foo; echo 5x5=$foo; ?>
// Outputs 5x5=25
// Outputs 5x5=25 // Outputs 5x5=$foo
Notice how echo 5x5=$foo outputs $foo rather than replacing it with 25 Strings in single quotes ( ) are not interpreted or evaluated by PHP This is true for both variables and character escape-sequences (such as \n or \\)
Data type
Data type
int, integer float, double string bool, Boolean array object Resource NULL
Description Whole numbers (i.e., numbers without a decimal point). Real numbers (i.e., numbers containing a decimal point). Text enclosed in either single ('') or double ("") quotes. True or false. Group of elements of the same type. Group of associated data and methods. An external data source. No value.
Get type
<?php $a = 1; $b = 1.2; $c = "abc"; echo gettype($a)."<br>"; echo gettype($b)."<br>"; echo gettype($c)."<br>"; ?>
Set type
<?php
$foo = "5bar"; // string $bar = true; // boolean
settype($foo, "integer"); // $foo is now 5 (integer) settype($bar, "string"); // $bar is now "1" (string) ?>
Set type
<?php $testString = 10.2abc; // call function settype to convert variable // testString to different data types print( "$testString" ); settype( $testString, "double" ); print( " as a double is $testString <br />" ); print( "$testString" ); settype( $testString, "integer" ); print( " as an integer is $testString <br />" ); settype( $testString, "string" ); print( "Converting back to a string results in $testString <br /><br />" ); 10.2abc as a double is 10.2 10.2 as an integer is 10 Converting back to a string results in 10
echo "Now using type casting instead: <br>"; echo "As a string - ".(string) $data ; echo "<br> As a double - ".(double) $data; echo "<br> As an integer - ".(integer) $data; ?>
?>
PHP Operators
The assignment operator = is used to assign values to variables in PHP. The arithmetic operator + is used to add values together in PHP. Assignment operators
Syntactical
Constants
Named values define function
PHP Operators
Arithmetic Operators Assignment Operators Incrementing/Decrementing Operators Comparison Operators Logical Operators
Arithmetic Operators
Operator Name Description Example Result x+y x-y Addition Subtraction Sum of x and y Difference of x and y 2+2 5-2 4 3
x*y
Multiplication
Product of x and y
5*2
10
x/y
Division
Quotient of x and y
15 / 5
x%y
Modulus
Remainder of x divided by y
1 2 0
-x a.b
Negation Concatenation
HiHa
Assignment Operators
Assignme nt x=y Same as... x=y Description The left operand gets set to the value of the expression on the right
x += y
x=x+y
Addition
x -= y
x *= y
x=x-y
x=x*y
Subtraction
Multiplication
x /= y
x %= y
x=x/y
x=x%y
Division
Modulus
a .= b
a=a.b
Arithmetic Operations
<?php $a=15; $b=30; $total=$a+$b; echo $total; echo<p><h1>$total</h1>; // total is 45 ?>
$a - $b $a * $b $a / $b $a += 5
Incrementing/Decrementing Operators
Operator Name Description
++ x
Pre-increment
x ++
Post-increment
-- x
Pre-decrement
x --
Post-decrement
Arithmetic Operations
<?php $a =1; echo $a++; // output 1,$a is now equal to 2 echo ++$a; // output 3,$a is now equal to 3 echo --$a; // output 2,$a is now equal to 2 echo $a--; // output 2,$a is now equal to 1
?>
Arithmetic Operations
<?php
$num1 = 10;
$num2 =20; // addition echo $num1+$mum2 . <br>; //subtraction echo $num1 - $num2 . <br>; // multiplication ?>
Arithmetic Operations
<?php // Multiplication echo $num1* $num2 . <br>; // Division
Arithmetic Operations
?>
that includes its type and value. Arrays and objects are explored recursively with values indented to show structure. <?php $b = 3.1; $c = true; var_dump($b); var_dump($c); //or var_dump($b,$c); ?>
Comparison Operators
Operator x == y x === y Name Equal Identical Description True if x is equal to y True if x is equal to y, and they are of same type True if x is not equal to y True if x is not equal to y True if x is not equal to y, or they are not of same type True if x is greater than y True if x is less than y Example 5==8 returns false 5==="5" returns false
x != y x <> y x !== y
x>y x<y
x >= y
x <= y
Comparison Operators
<?php var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" != "01"); // 1 != 1 -> false var_dump("10" == "1e1"); // 10 == 10 -> true var_dump("10" == "1ee1"); // 10 == 1 -> false var_dump(100 === "100"); // 100 == 100 -> false boolean true boolean false boolean true boolean false boolean false boolean true
Logical Operators
Operator x and y Name And Description True if both x and y are true Example x=6 y=3 (x < 10 and y > 1) returns true x=6 y=3 (x==6 or y==5) returns true x=6 y=3 (x==6 xor y==3) returns false x=6 y=3 (x < 10 && y > 1) returns true
x or y
Or
x xor y
Xor
x && y
And
x || y
Or
!x
Not
Logical Operators
<?php $a = (false && true); $b = (true || false); $c = (false and flase); $d = (true or true); boolean true boolean false boolean false boolean true
$e = false || true;
$f = false or true; var_dump($e, $f); $g = true && false; $h = true and false; var_dump($g, $h); ?>
quotation .
// define constant VALUE define( "VALUE", 5 ); // add constant VALUE to variable $a $a = $a + VALUE; print( "Variable a after adding constant VALUE is $a <br />" );
$a += $str;
print( "Adding a string to variable a yields $a <br />" ); ?>
Referencing Operators
We know the assignment operators work by value ,by copy the value to
other expression ,if the value in right hand change the value in left is not
change .
Ex:
<?php
$a =10; $b =$a; $b =20 Echo $a; // 10 ?>
Referencing Operators
But we can change the value of variable $a by the reference , that mena
Example: <?php
$a =10;
$b = &$a; $b= 20; echo $a; // 20 ?>
Very often when you write code, you want to perform different
actions for different decisions. You can use conditional statements in your code to do this.
if statement - executes some code only if a specified condition is true if...else statement - executes some code if a condition is true and another code if the condition is false if...else if....else statement - selects one of several blocks of code to be executed switch statement - selects one of many blocks of code to be executed
The if Statement
The if statement is used to execute some code only if a specified condition
is true.
if (condition) { code to be executed if condition is true; }
hello john
be executed.
if (condition) { code to be executed if condition is true; } else if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
executed.
switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; }
?>
PHP Loops
Loops execute a block of code a specified number of times, or while a
<?php $i=1; while($i<=5) { echo "The number is " . $i . "<br>"; $i++; } ?>
The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
then check the condition, and repeat the loop while the condition is true.
$i=1; The number do { The number $i++; The number echo "The number is " . $i . "<br>"; The number } The number while ($i<=5);
is 2 is 3 is 4 is 5 is 6
?>
The number is 2 The number is 3 The number is 4 The number is 5 The number is 6
Parameters: init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
Isset Function
bool isset ( $var ) Determine if a variable is set and is not NULL. If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULLbyte ("\0") is not equivalent to the PHP NULL constant. If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon
Isset Function
<?php $var = ''; // This will evaluate to TRUE so the text will be printed.
if (isset($var))
{ echo "This var is set so I will print.";
}
?>
Unset Function
void unset ( $var) unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
unset Function
<?php
$foo = 'bar'; echo $foo; unset($foo); echo $foo; ?>
phpinfo();
?>
Goto
<?php goto a; echo 'Foo'; a: echo 'Bar'; ?> <?php for($i=0,$j=50; $i<100; $i++) { while($j--) { if($j==17) goto end; } } echo "i = $i"; end: echo 'j hit 17'; ?>
Chapter Example
}
else { echo The variable foo is equal to .$foo; }
?>
Switch Statment
<?php $count=0; switch($count) { case 0: echo hello PHP3. ; break; case 1: echo hello PHP4. ; break; default: echo hello PHP5. ; break; } ?>
hello PHP3
Switch - Example
<?php $total = 0; $i = 2; switch($i) { case 6: $total = 99; break; case 1: $total += 1;break; case 2:$total += 2;break; case 3: $total += 3; ;break; case 4:$total += 4; break; default : $total += 5;break; } echo $total; ?>
For Loop
<?php $count=0; for($count = 0;$count <3,$count++) { Print hello PHP. ; } ?>
For - Example
<?php for ($i = 1; $i <= 10; $i++) { echo $i; }
?>
For-Example
<?php $brush_price = 5; echo "<table border=\"1\" align=\"center\">"; echo "<tr><th>Quantity</th>"; echo "<th>Price</th></tr>"; for ( $counter = 10; $counter <= 100; $counter += 10) { echo "<tr><td>"; echo $counter; echo "</td><td>"; echo $brush_price * $counter; echo "</td></tr>"; } echo "</table>"; ?>
While Loop
<?php $count=0; while($count<3) { echo hello PHP. ; $count += 1; // $count = $count + 1; // or // $count++; } ?>
While - Example
<?php $i = 0; while ($i++ < 5) { echo loop number : .$i; } ?>
Do..While
<?php $i = 0; do { echo $i; } while ($i > 0); ?>
For..If
<?php $rows = 4; echo '<table><tr>'; for($i = 0; $i < 10; $i++){ echo '<td>' . $i . '</td>'; if(($i + 1) % $rows == 0){ echo '</tr><tr>';
}
} echo '</tr></table>'; ?>
For
<?php //this is a different way to use the 'for' //Essa uma maneira diferente de usar o 'for' for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){ $p = $i + $x;
Nested For
<?php for($a=0;$a<10;$a++){ for($b=0;$b<10;$b++){ for($c=0;$c<10;$c++){ for($d=0;$d<10;$d++){ echo $a.$b.$c.$d.", "; } } } } ?>
While - Switch
<?php $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* Exit the switch and the while. */ default: break; } } ?>
Continue
<?php for ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$i\n"; } ?>
If - Switch
<?php $i = 1; if ($i == 0) { echo "i equals } elseif ($i == 1) echo "i equals } elseif ($i == 2) echo "i equals } 0"; { 1"; { 2";
switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } ?>
Do..While - IF
<?php do { if ($i < 5) { echo "i is not big enough"; break; } $i *= $factor; if ($i < $minimum_limit) { break; } echo "i is ok"; /* process i */ } while (0); ?>
If in other style
<?php $hour = 11; echo $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!"; ?>