Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basics (Cont...).

Similar presentations


Presentation on theme: "Basics (Cont...)."— Presentation transcript:

1 Basics (Cont...)

2 PHP Arrays An array can store one or more values in a single variable name. When working with PHP, sooner or later, you might want to create many similar variables. Instead of having many similar variables, you can store the data as elements in an array. Each element in the array has its own ID so that it can be easily accessed. There are three different kind of arrays: Numeric array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays

3 PHP Arrays A numeric array stores each element with a numeric ID key.
There are different ways to create a numeric array. In this example the ID key is automatically assigned: $names = array("Peter","Quagmire","Joe"); In this example we assign the ID key manually: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";

4 PHP Arrays The ID keys can be used in a script:
Numeric Arrays The ID keys can be used in a script: <?php $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbours"; ?> The code above will output: Quagmire and Joe are Peter's neighbours

5 PHP Arrays Associative Arrays An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them. In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

6 PHP Arrays Associative Arrays
This example is the same as example 1, but shows a different way of creating the array: $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";

7 PHP Arrays The ID keys can be used in a script:
Associative Arrays The ID keys can be used in a script: <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?> The code above will output: Peter is years old.

8 PHP Arrays Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. In the next example we create a multidimensional array, with automatically assigned ID keys:

9 PHP Arrays Multidimensional Arrays $families = array (
"Griffin"=>array "Peter", "Lois", "Megan" ), "Quagmire"=>array "Glenn" "Brown"=>array "Cleveland", "Loretta", "Junior" ) );

10 PHP Arrays Multidimensional Arrays The array above would look like this if written to the output: Array ( [Griffin] => Array [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array [0] => Glenn [Brown] => Array [0] => Cleveland [1] => Loretta [2] => Junior

11 PHP Arrays Lets try displaying a single value from the array above:
Multidimensional Arrays Lets try displaying a single value from the array above: echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; The code above will output: Is Megan a part of the Griffin family?

12 PHP Looping Looping statements in PHP are used to execute the same block of code a specified number of times. Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this. In PHP we have the following looping statements: while - loops through a block of code if and as long as a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array

13 PHP Looping The while Statement - Syntax
The while statement will execute a block of code if and as long as a condition is true. while (condition) code to be executed;

14 PHP Looping The while Statement - Example The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html>

15 PHP Looping The do...while Statement - Syntax
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true. do { code to be executed; } while (condition);

16 PHP Looping The do...while Statement - Example The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5: <html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html>

17 PHP Looping The for Statement - Syntax
The for statement is used when you know how many times you want to execute a statement or a list of statements. for (initialization; condition; increment) { code to be executed; }

18 PHP Looping The for Statement - Example The following example prints the text "Hello World!" five times: <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html>

19 PHP Looping The foreach statement is used to loop through arrays.
The foreach Statement - Syntax The foreach statement is used to loop through arrays. For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element. foreach (array as value) { code to be executed; }

20 PHP Looping The foreach Statement - Example
The following example demonstrates a loop that will print the values of the given array: <html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html>

21 PHP User-defined Functions
Functions, like all PHP code, must be contained within <?php ... ?> tags. Function is defined when a block of code is needed to execute again and again in a program. A parameter is a variable that is used within a function. Parameters are placed within the parentheses that follow the function name. Functions do not have to must contain parameters. The set of curly braces (called function braces) contain the function statements. Function statements do the actual work of the function and must be contained within the function braces.

22 PHP User-defined Functions
Creating a simple PHP Function A simple function that print University name when it is called: <html> <body> <?php function UniName() { echo “university of Gujrat"; } UniName(); ?> </body> </html>

23 PHP User-defined Functions
PHP Functions - Adding parameters Our first function UniName() is a very simple function. It only writes a static string. To add more functionality to a function, we can add parameters. A parameter is just like a variable. You may have noticed the parentheses (brackets!) after the function name, like: UniName(). The parameters are specified inside the parentheses. A function can have more than one parameters separated by “,”

24 PHP User-defined Functions
PHP Functions - Adding parameters The following example will write different first names, but the same last name: <?php function writeMyName($fname) { echo $fname . " Smith.<br />"; } echo "My name is "; writeMyName("John"); writeMyName("Sarah"); writeMyName("Smith"); ?> The output of the code will be: My name is John smith. My name is Sarah Smith. My name is Smith Smith.

25 PHP User-defined Functions
PHP Functions - Return values A return statement is a statement that returns a value to the statement that called the function. A function does not necessarily have to return a value. <html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo " = " . add(1,16); ?> </body> </html> The output of the code will be: = 17

26 PHP User-defined Functions
PHP Functions - values and references for most data types, return values are passed by value for objects, discussed next week, return values are returned by reference the following function describe the difference between pass by value and pass reference: function increment_value($y) { $y++; echo "$y</br>"; } function increment_reference(&$y) { $y++; echo "$y</br>"; } $x = 1; increment_value($x); echo "$x</br>"; increment_reference($x); echo "$x</br>"; run code what will be the output of the above program?

27 PHP User-defined Functions
PHP Functions - scope scoping is way of avoiding name clashes between variables in different functions each function code block belongs to a certain scope variables within functions have local scope and are private to the function variables outside a function have a global scope and are available anywhere in the program <?php $a = 1; // global scope function test(){ echo $a; // reference to …?... scope variable } test(); ?> run code what will be the output of the above program?

28 PHP User-defined Functions
PHP Functions - scope the global keyword will be used to access variables from the global scope within functions <?php $a = 1; $b = 2; function sum(){ global $a, $b; $b = $a + $b; } sum(); echo $b; ?> what will be the output of the above program? The above script will output 3. Because of declaring $a and $b global within the function, all references to either variable will refer to the global version

29 PHP User-defined Functions
PHP Functions - default values a function can use a default value in an argument using the = sign to precede the argument consider the following example <?php function setName($FirstName = “xyz", $LastName = “Adam") { echo "Hello, $FirstName $LastName!\n"; } // So to greet someone called “xyz Adam”, you just call the function as: setName(); // To greet someone may be brother of xyz as “abc Adam” setName(“abc”); //To greet someone else named “Umer Farooq” setName(“Umer”, “Farooq”); run code

30 PHP User-defined Functions
PHP Functions - anonymous functions (run-time or dynamically created functions) it is possible for PHP to use the value of an input (e.g. from a form) and change the definition of a function based on the input. Create_function() is used for creating dynamic function. Syntax: create_function(‘arguments’,’code’); <?php $fn = create_function('$arg_1,$arg_2', '$res = $arg_1+$arg_2; echo $res;'); echo $fn."</br>"; // print dynamically created function name echo $fn(10,20)."</br>"; //execute code used within the dynamically created function run code Note the above example also illustrates how you can store a function name in a variable.

31 Including and Requiring PHP files
PHP allows to reuse any type of code (including functions, classes): Can insert code from a file into your PHP script by using the following php functions include (‘filename’); require (‘filename’); include_once (‘filename’); require_once (‘filename’); Statements include() & require() are similar, except when they fail: include() will produce an E_WARNING and continue remaining code rendering require() will die with fatal E_ERROR and stop execution further Can also use variations include_once() or require_once() to avoid problems with redundancy; eg. redefining same function repeatedly Slower than include()/require()

32 Including and Requiring PHP files
require and require_once functions When using include and include_once, if the including PHP files is not exist, PHP post a warning and try to execute the program Require and require_once is used to make sure that a file is included and to stop the program if it isn’t

33 Implode() and Explode() Functions in PHP
Implode() Function The implode function is used to "join elements of an array with a string“ The implode function in PHP is easily remembered as "array to string", which simply means that it takes an array and returns a string. Syntax: implode (separator , array) <?php $arr=array (‘This',‘was',‘an',‘array'); echo implode(“ “,$arr); echo implode(" - ", $arr); ?> run code The output of the above code: This was an array This-was-an-array

34 Implode() and Explode() Functions in PHP
The explode function is used to "Split a string by a specified string into pieces i.e. it breaks a string into an array" The explode function in PHP is easily remembered as “string to array", which simply means that it takes a String and returns an array. Syntax: explode (separator,string) <?php $str=“This was a String"; print_r(explode(" ",$str)); ?> run code The output of the above code: Array( [0] => This [1] => was [2] => a [3] => String ) Note: The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.


Download ppt "Basics (Cont...)."

Similar presentations


Ads by Google