PHP is a recursive acronym for PHP Hypertext
- Slides: 103
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP, Perl, JSP
What is PHP? • PHP is an acronym for "PHP: Hypertext Preprocessor" • PHP is a widely-used, open source scripting language • PHP scripts are executed on the server • PHP is free to download and use • It is integrated with a number of popular databases, including My. SQL, Postgre. SQL, Oracle, Sybase, Informix, and Microsoft SQL Server. • Very good for creating dynamic content • PHP Syntax based on Perl, Java, and C
What is a PHP File? • PHP files can contain text, HTML, CSS, Java. Script, and PHP code • PHP code are executed on the server, and the result is returned to the browser as plain HTML • PHP files have extension ". php"
Common uses of PHP • PHP can generate dynamic page content • PHP can create, open, read, write, delete, 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 be used to control user-access • PHP can encrypt data
Why PHP? • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc. ) • PHP is compatible with almost all servers used today (Apache, IIS, etc. ) • PHP supports a wide range of databases • PHP is free. Download it from the official PHP resource: www. php. net • PHP is easy to learn and runs efficiently on the server side
What Do I Need? To start using PHP, you can: • Find a web host with PHP and My. SQL support (Internet) or • Install a web server on your own PC, and then install PHP and My. SQL (Local Machine)
PHP on the Internet • Find the proper web host on the internet • Mostly all the hosting service providers would support the PHP. Check the Web host support of PHP • Upload and run the php file • %php -v , if PHP installed, we’ll see the PHP version and date displayed like this. PHP 5. 2. 0 (cli) (built: Nov 2 2006 11: 57: 36) Copyright (c) 1997 -2006……………. ………………………………. .
Set Up PHP on Your Own PC : Method 1 • Install a web server • install PHP • install a database, such as My. SQL • installation instructions for PHP: http: //php. net/manual/en/install. php
Set Up PHP on Your Own PC : Method 2 Installing XAMPP. • XAMPP is the most popular PHP development environment • XAMPP is a completely free, easy to install Apache distribution containing Maria. DB, PHP, and Perl. The XAMPP open source package has been set up to be incredibly easy to install and to use. • Acronym for • • • X (any Operating System), Apache (Web server), My. SQL Database or Maria Database, PHP Language PERL https: //www. apachefriends. org/index. html
Set Up PHP on Your Own PC : Method 3 Installing WAMP. • Wamp. Server is a Windows web development environment. • It allows you to create web applications with Apache 2, PHP and a My. SQL database. Alongside, Php. My. Admin allows you to manage easily your databases. • Acronym for • • Windows Operating System Apache(Web server) My. SQL Database PHP Language http: //www. wampserver. com/en/
Creating Your Development Environment • Consider, every thing required for php script execution is installed. How to create the PHP file. • Use text editor to write the PHP script and save the file with the extension of. php Example (resume. php) List of some suggested editors: • • Vi Emacs Pico Macintosh’s BBEdit or Simple. Text Windows Notepad Wordpad Sublime Text ( Recommended) The text editor needs to be able to save files in Plain Text Format (Text without any special formatting codes)
We can use the IDE to creat PHP file. • • Komoda Maguma PHPEdit Zend Studio • Most of them will cost money, although they have some good features for php development.
Creating First PHP Page • A PHP script can be placed anywhere in the document. • A PHP script starts with <? php and ends with ? > <? php ………………………. . . ? > PHP statements end with a semicolon (; ).
Example 1 <? phpinfo(); ? >
Running Your First PHP Page • Make sure web server is running • Deploy your php project into the htdocs folder(If XAMPP) / www folder (If WAMP) • Access your php file in browser using below syntax. localhost: /project folder name/filename. php
Mixing HTML with PHP • One of the charms of PHP is that, we can intersperse our PHP code with HTML. • HTML will be displayed by the browser, PHP will be run on your server – and if that PHP generates some HTML, that HTML will be displayed in the browser as well.
Only HTML with PHP <html> <head> <title> Using PHP and HTML together </title> </head> <body> <h 1> Using PHP and HTML together </h 1> </body> Here is your PHP info: <? php </html> phpinfo(); ? > </body> </html>
Comments in PHP <? php // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */
Variables • In PHP, a variable starts with the $ sign, followed by the name of the variable: <!DOCTYPE html> <body> <? php $txt = "Hello world!"; $x = 5; $y = 10. 5; echo $txt; echo " "; echo $x; echo " "; echo $y; ? > </body> </html> Note: When you assign a text value to a variable, put quotes around the value. Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
Rules for PHP variables: • A variable starts with the $ sign, followed by the name of the variable • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0 -9, and _ ) • Variable names are case-sensitive ($age and $AGE are two different variables) • Remember that PHP variable names are case-sensitive!
PHP is a Loosely Typed Language • In the example above, notice that we did not have to tell PHP which data type the variable is. • PHP automatically converts the variable to the correct data type, depending on its value. • In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.
PHP Variables Scope • In PHP, variables can be declared anywhere in the script. • The scope of a variable is the part of the script where the variable can be referenced/used. • PHP has three different variable scopes: • local • global • static
Global and Local Scope • A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: • A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function: <? php $x = 5; // global scope function my. Test() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } my. Test(); echo "<p>Variable x outside function is: $x</p>"; ? > <? php function my. Test() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } my. Test(); // using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>"; ? >
PHP The global Keyword • The global keyword is used to access a global variable from within a function. • To do this, use the global keyword before the variables (inside the function): <? php $x = 5; $y = 10; function my. Test() { global $x, $y; $y = $x + $y; } my. Test(); echo $y; // outputs 15 ? >
$GLOBALS[index] • PHP also stores all global variables in an array called $GLOBALS[index]. • The index holds the name of the variable. • This array is also accessible from within functions and can be used to update global variables directly.
<? php $x = 5; $y = 10; function my. Test() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } my. Test(); echo $y; // outputs 15 ? >
Static Keyword • Student Task
echo and print Statements • echo and print are more or less the same. They are both used to output data to the screen. Difference between echo and print • echo has no return value while print has a return value of 1 so it can be used in expressions. • echo can take multiple parameters (although such usage is rare) while print can take one argument. • echo is marginally faster than print.
echo statement The echo statement can be used with or without parentheses: echo or echo() echo "Hello world!”; echo ("Hello world!");
<!DOCTYPE html> <body> <? php $txt 1 = "Learn PHP"; $txt 2 = “SRM"; $x = 5; $y = 4; echo "<h 2>". $txt 1. "</h 2>"; echo "Study PHP at ". $txt 2. " "; echo $x + $y; ? > </body> </html>
Data type Variables can store data of different types, and different data types can do different things. PHP supports the following data types: • String • Integer • Float (floating point numbers - also called double) • Boolean • Array • Object • NULL • Resource
• PHP String • A string is a sequence of characters, like "Hello world!". • A string can be any text inside quotes. You can use single or double quotes: <? php $x = "Hello world!"; $y = 'Hello world!'; echo $x; echo " "; echo $y; ? >
• PHP Integer • An integer data type is a non-decimal number between -2, 147, 483, 648 and 2, 147, 483, 647. Rules for integers: • • An integer must have at least one digit An integer must not have a decimal point An integer can be either positive or negative Integers can be specified in three formats: decimal (10 -based), hexadecimal (16 based - prefixed with 0 x) or octal (8 -based - prefixed with 0)
<? php $x = 5985; var_dump($x); ? > int(5985)
• PHP Float • A float (floating point number) is a number with a decimal point or a number in exponential form. • In the following example $x is a float. The PHP var_dump() function returns the data type and value: <? php $x = 10. 412; var_dump($x); ? > float(10. 412)
PHP Boolean • A Boolean represents two possible states: TRUE or FALSE. • $x = true; $y = false; • Booleans are often used in conditional testing $x = true; var_dump($x);
• PHP Array • An array stores multiple values in one single variable. $cars = array("Volvo", "BMW", "Toyota"); var_dump($cars); array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
• PHP Object • An object is a data type which stores data and information on how to process that data. • In PHP, an object must be explicitly declared. <? php class Car { function Car() { $this->model = "VW"; } } // create an object $herbie = new Car();
PHP NULL Value • Null is a special data type which can have only one value: NULL. • A variable of data type NULL is a variable that has no value assigned to it. • Tip: If a variable is created without a value, it is automatically assigned a value of NULL. <? php $x = "Hello world!"; $x = null; var_dump($x); ? >
PHP Resource • The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP. • A common example of using the resource data type is a database call.
PHP 5 - Strings • A string is a sequence of characters, like "Hello world!“ PHP String Functions • functions are used to manipulate the strings. 1. Get The Length of a String <? php echo strlen("Hello world!"); // outputs 12 ? > 2. Number of Words in a String <? php echo str_word_count("Hello world!"); // outputs 2 ? >
3. Reverse a String <? php echo strrev("Hello world!"); // outputs !dlrow olle. H ? > For More String Functions: Please Refer https: //www. w 3 schools. com/php_ref_string. asp
Constant
Operators • Math Operators • Basic Operators (+, -, *, /, %) • Math Functions (Predefined functions – example : max, sqrt, sin…etc) • Assignment Operator • Normal Assignment (=) • Combination Assignment (+=, -=, /=, … etc) • • Increment and Decrement Operator (++, --) String Operators (. , . = ) Bitwise Operators (&, |, ^, ~, <<, >>) Execution Operator (`) Comparison Operators (==, ===, !=, <>, >, <, <=, >=) Logical Operator (and, or, xor, !, &&, ||) Ternary Operator
Math Operators (Arithmetic Operators) <? php echo "7 + 2 = ", 7 + 2, " "; echo "7 - 2 = ", 7 - 2, " "; echo "7 * 2 = ", 7 * 2, " "; echo "7 / 2 = ", 7 / 2, " "; echo "7 % 2 = ", 7 % 2, " "; ? > 7 + 2 = 9 7 - 2 = 5 7 * 2 = 14 7 / 2 = 3. 5 7 % 2 = 1
Math Functions <? php echo "pow(4, 3) = ", pow(4, 3), " "; echo "floor(3. 14159) = ", floor(3. 14159), " "; echo "dechex(16) = ", dechex(16), " "; ? pow(4, 3) = 64 floor(3. 14159) = 3 dechex(16) = 10
Assignment Operator • Used to assign the value to variable. $name = “David”; Multiple assignment on the same line. $a = $b = $c = $d = 10;
Combination Assignment $a = 3; $a = $a + 6; a += 6; Similarly, -= *= /=. = %= &= |= ^= <<= >>= $a = “Hello”; $a. = “David”; Now the $a becomes “Hello David”
Increment and Decrement Operator (++, --) ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one
Increment and Decrement Operator (++, --) <? php $a = $b = $c = $d = 1; $a = $b = $c = $d = 1 echo "$a = $b = $c = $d = 1 "; echo "$a++ gives ", $a++, " "; echo "Now $a = ", $a, " "; echo "++$b gives ", ++$b, " "; echo "$c-- gives ", $c--, " "; echo "Now $c = ", $c, " "; echo "--$d gives ", --$d, " "; ? > Now $a = 2 $a++ gives 1 ++$b gives 2 $c-- gives 1 Now $c = 0 --$d gives 0
String Operators (. , . = ). Concatenation $txt 1. $txt 2 Concatenation of $txt 1 and $txt 2 . = Concatenation assignment $txt 1. = $txt 2 Appends $txt 2 to $txt 1 <? php $a = "No "; echo "$a = ", $a, " "; echo "$b = $a. "worries " "; $b = $a. "worries "; echo "Now $b = ", $b, " "; echo "$b. = "at all. " "; $b. = "at all. "; echo "Now $b = ", $b, " "; ? > $a = No $b = $a. "worries " Now $b = No worries $b. = "at all. " Now $b = No worries at all.
Comparison Operators Operator Name Example Result == Equal $x == $y Returns true if $x is equal to $y === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type != Not equal $x != $y Returns true if $x is not equal to $y <> Not equal $x <> $y Returns true if $x is not equal to $y !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or equal $x >= $y to Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
Identical Operator: Not identical Operator: <? php $x = 100; $y = "100"; var_dump($x === $y); // returns false because types are not equal ? > var_dump($x !== $y); // returns true because types are not equal ? > Not equal Operator: Difference Between != and <> : <? php $x = 100; $y = "100"; <> and != are 100% interchangeable, and var_dump($x <> $y); // returns false because values are equal ? > there's absolutely no technical reason to use one over the other.
Logical Operators PHP logical operators are used to combine conditional statements. Operator Name Example Result and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true <? php $x = 100; $y = 50; if ($x == 100 and $y == 50) { echo "Hello world!"; } ? > Difference between (and , &&) and (or, ||) : &&, || having high precedence than “and”, “or” respectively.
Bitwise Operators • This operators can work with the individual bits inside numbers Operator Operation Results $a & $b And Bits that are set in both $a and $b are set $a | $b Or Bits that are set in either $a or $b are set. $a ^ $b Xor Bits that are set in $a or $b but not both are set. ~ $a Not Bits that are set in $a are not set, and vice versa. $a << $b Shift Left Shift the bits of $a, $b steps to the left (Each steps means “multiply by two”) $a >> $b Shift Right Shift the bits of $a, $b steps to the right (Each steps means “divide by two”)
Ternary Operator if( $valid ) { $x = 'yes'; } else { $x = 'n o'; } If $valid is true set $x to yes, otherwise set it to no. But this example is rather long for such a simple assignment. Let's do it in one line with ternary logic: $x = $valid ? 'yes' : 'no'; $result = condition ? expression 1: expression 2;
Execution Operator • PHP supports one execution operator: backticks (``) • Note that these are not single-quotes! • PHP will attempt to execute the contents of the backticks as a shell command; • This backticks used to execute the system commands. <? php $output = `dir d: `; echo "<pre>$output</pre>"; ? > Reference: http: //php. net/manual/en/language. operators. execution. php
Operator Precedence <? php echo "4 + 3 * 9 = ", 4 + 3 * 9, " "; echo "(4 + 3) * 9 = ", (4 + 3) * 9, " "; ? > 4 + 3 * 9 = 31 (4 + 3) * 9 = 63 Operators clone new [ ** ++ -- ~ (int) (float) (string) (array) (object) (bool) @ instanceof ! * / % + -. << >> < <= > >= == != === !== <> <=> & ^ | && || ? ? ? : = += -= *= **= /=. = %= &= |= ^= <<= >>= and xor or Additional Information clone and new array() arithmetic types and increment/decrement types logical arithmetic and string bitwise comparison bitwise and references bitwise logical comparison ternary assignment logical
Array Operators The PHP array operators are used to compare arrays. Operator Name Example Result + Union $x + $y Union of $x and $y == Equality $x == $y Returns true if $x and $y have the same key/value pairs === Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types != Inequality $x != $y Returns true if $x is not equal to $y <> Inequality $x <> $y Returns true if $x is not equal to $y !== Non-identity $x !== $y Returns true if $x is not identical to $y
Program Control Conditional Statement or Selection Statement Looping Statement
Conditional Statement or Selection Statement • If…. else Statement • if. . . elseif. . else Statement • Switch
Syntax if (condition) { code to be executed if condition is true ; } if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
switch (n) { case label 1: code to be executed if n=label 1; break; case label 2: code to be executed if n=label 2; break; case label 3: code to be executed if n=label 3; break; . . . default: code to be executed if n is different from all labels; } Note: PHP Switch allows the String. And that switch/case does loose comparison. the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2. It will check only the value not the data type.
<!DOCTYPE html> <body> <? php $a=10; $b=20; $c=30; If($a>$b) { If($a>$c) print “a is largest”; else Print “c is largest”; } else { If($b>$c) print “b is largest”; else print ” c is largest”; } ? > </body> </html>
<!DOCTYPE html> <body> <? php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ? > </body> </html> Output: Your favorite color is red!
Looping Structure • for • while • do-while (condition is true) { code to be executed; } do { code to be executed; } while (condition is true); These are Traditional Looping for (init counter; test counter; increment counter) { code to be executed; }
<!DOCTYPE html> <body> <? php $x = 1; while($x <= 5) { echo "The number is: $x "; $x++; } ? > </body> </html> Output: The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5
<!DOCTYPE html> <body> Output: <? php $x = 6; do { echo "The number is: $x "; $x++; } while ($x <= 5); ? > </body> </html> The number is: 6
<!DOCTYPE html> <body> <? php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x "; } ? > </body> </html> Output: The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9 The number is: 10
More in for loop can handle multiple loop counters if we want, as long as you separate them with the comma operator. It can be used to fetch the record from data base. for($loop 1=2, $loop 2=2 ; $loop 1<6 && $loop 2<6 ; $loop 1++, $loop 2++) { }
foreach loop • The foreach loop works only on collections, such as arrays, and is used to loop through each key/value pair in an array. foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element. <? php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value "; } ? > red green blue yellow
Terminating Loop early (using break) • The loop and switch statement can be stopped any time using break statement. <? php for($i=1; $i<=10; $i++) { echo "$i <br/>"; if($i==5) { break; } } ? > 1 2 3 4 5
Skipping iteration (using continue) <? php $x=1; echo 'List of odd numbers between 1 to 10 <br />'; while ($x<=10) { if (($x % 2)==0) { Output $x++; List of odd numbers between 1 to 10 continue; 1 } 3 else 5 { 7 echo $x. '<br />'; 9 $x++; } }
PHP Alternate Syntax • PHP offers an alternative syntax for some of its control structures; namely, • • • if while, foreach switch <? php for($i = 1; $i <= 10; $i++) : Echo $i; endfor; ? > • In each case, the basic form of the alternate syntax is to change the opening brace to a colon (: ) and the closing brace to endif; , endwhile; , endfor; , endforeach; , or endswitch; , respectively.
PHP Array • An array stores multiple values in one single variable: • If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars 1 = "Volvo"; $cars 2 = "BMW"; $cars 3 = "Toyota"; And what if you had not 3 cars, but 300? The solution is to create an array!
Create an Array in PHP array(); In PHP, the array() function is used to create an array: <? php $cars = array("Volvo", "BMW", "Toyota"); echo "I like ". $cars[0]. ", ". $cars[1]. " and ". $cars[2]. ". "; ? >
Types of arrays: • Indexed arrays - Arrays with a numeric index • Associative arrays - Arrays with named keys • Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays • The index can be assigned automatically (index always starts at 0), like this: • $cars = array("Volvo", "BMW", "Toyota"); • or the index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota";
PHP Associative Arrays • Associative arrays are arrays that use named keys that you assign to them. • There are two ways to create an associative array: $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); or: $age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe'] = "43"; <? php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is ". $age['Peter']. " years old. "; ? >
Multidimensional Arrays A multidimensional array is an array containing one or more arrays. The dimension of an array indicates the number of indices you need to select an element. • For a two-dimensional array you need two indices to select an element • For a three-dimensional array you need three indices to select an element
First, take a look at the following table: Name Stock Sold Volvo 22 18 BMW 15 13 Saab 5 2 Land Rover 17 15 We can store the data from the table above in a two-dimensional array, like this: $cars = array ( array("Volvo", 22, 18), array("BMW", 15, 13), array("Saab", 5, 2), array("Land Rover", 17, 15) ); <? php echo $cars[0][0]. ": In stock: ". $cars[0][1]. ", sold: ". $cars[0][2]. ". "; echo $cars[1][0]. ": In stock: ". $cars[1][1]. ", sold: ". $cars[1][2]. ". "; echo $cars[2][0]. ": In stock: ". $cars[2][1]. ", sold: ". $cars[2][2]. ". "; echo $cars[3][0]. ": In stock: ". $cars[3][1]. ", sold: ". $cars[3][2]. ". "; ? > $cars array contains four arrays, and it has two indices: row and column.
Handling Array with loop • Get The Length of an Array - using count() Function • $cars = array("Volvo", "BMW", "Toyota"); $arrlength = count($cars);
Loop Through an Indexed Array <? php $cars = array("Volvo", "BMW", "Toyota"); $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo " "; } ? >
Using foreach loop • <? php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value"; } ? >
Loop Through an Associative Array <? php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=". $x. ", Value=". $x_value; echo " "; } ? >
Sorting Arrays sort() - sort arrays in ascending order rsort() - sort arrays in descending order asort() - sort associative arrays in ascending order, according to the value ksort() - sort associative arrays in ascending order, according to the key arsort() - sort associative arrays in descending order, according to the value • krsort() - sort associative arrays in descending order, according to the key • • •
Some Important Functions in Array extract() – Extract data from the array and store it in variables. <? php $ice_cream["good"] = "orange"; $ice_cream["better"] = "vanilla"; $ice_cream["best"] = "rum raisin"; extract($ice_cream); echo $good; echo $better; echo $best; ? >
Student Task • array_diff () • array_diff_assoc () • array_slice () • array_merge() • array_sum() • print_r() • implode() • explode() • unset()
Functions (User defined) • A function is a block of statements that can be used repeatedly in a program. • A function will not execute immediately when a page loads. • A function will be executed by a call to the function. • PHP has more than 1000 built-in functions.
Syntax function. Name() { code to be executed; } A function name can start with a letter or underscore (not a number).
Example <? php function write. Msg() { echo "Hello world!"; } write. Msg(); // call the function ? > Hello world!
Example (Function with arguments) <? php function family. Name($fname, $year) { echo "$fname Refsnes. Born in $year "; } family. Name("Hege", "1975"); family. Name("Stale", "1978"); family. Name("Kai Jim", "1983"); ? > Hege Refsnes. Born in 1975 Stale Refsnes. Born in 1978 Kai Jim Refsnes. Born in 1983
PHP Default Argument Value <? php function set. Height($minheight = 50) { echo "The height is : $minheight "; } set. Height(350); set. Height(); // will use the default value of 50 set. Height(135); set. Height(80); ? >
PHP Functions - Returning values <? php function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = ". sum(5, 10). " "; echo "7 + 13 = ". sum(7, 13). " "; echo "2 + 4 = ". sum(2, 4); ? > 5 + 10 = 15 7 + 13 = 20 2 + 4 = 6
Student Task – Array Function • PHP array_diff() Function Parameter Description array 1 Required. The array to compare from array 2 Required. An array to compare against Syntax array 3, . . . array_diff(array 1, array 2, array 3. . . ); Optional. More arrays to compare against The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array 1 that are not present in array 2 or array 3, etc. Return Value: Returns an array containing the entries from array 1 that are not present in any of the other arrays
array_diff_assoc() Syntax array_diff_assoc(array 1, array 2, array 3. . . ); The array_diff_assoc() function compares the keys and values of two (or more) arrays, and returns the differences. This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array 1 that are not present in array 2 or array 3, etc. Return Value: Returns an array containing the entries from array 1 that are not present in any of the other arrays
<? php $a 1=array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow"); $a 2=array("a"=>"red", "f"=>"green", "g"=>"blue"); $a 3=array("h"=>"red", "b"=>"green", "g"=>"blue"); $result=array_diff_assoc($a 1, $a 2, $a 3); print_r($result); ? > Array ( [c] => blue [d] => yellow )
array_slice () Syntax array_slice(array, start, length, preserve) Parameter Description array Required. Specifies an array start length preserve Required. Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array. Optional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter. • Optional. Specifies if the function should preserve or reset the keys. Possible values: true - Preserve keys • false - Default. Reset keys
$a=array("red", "green", "blue", "yellow", "brown"); $b=(array_slice($a, 2, 2, false)); print_r($b); Array ( [0] => blue [1] => yellow )
Implode() • The implode function is used to "join elements of an array with a string". • The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice. $arr = Array ("A", "E", "I", "O", "U"); To combine it into a string, by putting the separator '-' between each element of the array. $str = implode("-", $arr); A-E-I-O-U Syntax implode (separator , array)
Explode() • The explode() function breaks a string into an array. Syntax explode(separator, string, limit) Parameter Description separator Required. Specifies where to break the string Required. The string to split limit Optional. Specifies the number of array elements to return. Possible values: • Greater than 0 - Returns an array with a maximum of limit element(s) • Less than 0 - Returns an array except for the last -limit elements() • 0 - Returns an array with one element
$str = 'one, two, three, four'; $value= explode(', ', $str); print_r($value) Array ( [0] => one [1] => two [2] => three [3] => four )
print_r() function • The print_r() function is used to print human-readable information about a variable.
- Php stands for
- Hypertext processor
- Php hypertext preprocessor definition
- Php hypertext preprocessor
- All prepocessor commands begin with a
- Php hypertext preprocessor
- Php stand for
- What php stand for
- What is preprocessor in php
- Recursive and non recursive algorithm
- Php singkatan
- Php is an acronym for
- Hypertext significato
- Html stands for
- Personal hypertext processor
- Standar format untuk dokumen hypertext
- Patchwork girl hypertext
- Format yang dipakai untuk membuat dokumen hypertext
- Hypertext and hypermedia in multimedia
- Hypertext vs hypermedia
- Td vs th
- Example of hypertext
- Hypertext in print media example
- Hypermedia vs hypertext
- Advantages of hypertext
- Define hypertext and hypermedia
- Definition of hypertext
- Text tula
- Web.facebook.com.php
- Php php://input
- Fspos
- Orubbliga rättigheter
- Bamse för de yngsta
- Verktyg för automatisering av utbetalningar
- Ministerstyre för och nackdelar
- Tillitsbaserad ledning
- Vem räknas som jude
- Kolopskopi
- Ro i rom pax
- Stig kerman
- Verksamhetsanalys exempel
- Modell för handledningsprocess
- Shingelfrisyren
- Matematisk modellering eksempel
- Shivaismen
- Cks
- Inköpsprocessen steg för steg
- Jag har gått inunder stjärnor text
- Strategi för svensk viltförvaltning
- Sura för anatom
- Typiska novell drag
- Formel gruplar
- Rutin för avvikelsehantering
- Tack för att ni har lyssnat
- Läkarutlåtande för livränta
- Klassificeringsstruktur för kommunala verksamheter
- Mall för debattartikel
- Påbyggnader för flakfordon
- Tack för att ni lyssnade
- En lathund för arbete med kontinuitetshantering
- Tobinskatten för och nackdelar
- Egg för emanuel
- Tack för att ni har lyssnat
- Lågenergihus nyproduktion
- Mitos steg
- Presentera för publik crossboss
- Rbk-mätning
- Myndigheten för delaktighet
- Kung som dog 1611
- Vad är densitet
- Nationell inriktning för artificiell intelligens
- Tack för att ni har lyssnat
- Hur ser ett referat ut
- Karttecken höjdkurva
- Epiteltyper
- Magnetsjukhus
- Tryck formel
- Enheter för massa
- Underlag för särskild löneskatt på pensionskostnader
- Toppslätskivling effekt
- Elektronik för barn
- Borra hål för knoppar
- Mat för idrottare
- Smärtskolan kunskap för livet
- Bris för vuxna
- Vad är ett minoritetsspråk
- Ledarskapsteorier
- Frgar
- Humanitr
- Datorkunskap för nybörjare
- Rita perspektiv
- Returpilarna
- Redogör för vad psykologi är
- Lek med former i förskolan
- Bästa kameran för astrofoto
- Dikter
- Nyckelkompetenser för livslångt lärande
- Publik sektor
- Fredsgudinna pax
- Personlig tidbok för yrkesförare
- Capiche definition
- Assembly
- Exponentiation adalah
- Recursive sequence