0% found this document useful (0 votes)
44 views57 pages

PHP Notes

Uploaded by

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

PHP Notes

Uploaded by

nchaudhari9922
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 57
(Comeinurt Ghat a Wh PUP | Eeneral purpose scripting language especially suited to web development + PHI stands tor PLP hypertext preprocessor © PHP isa server side Programming language that is embedded in HTML © Pup allows web developers to cr session mana; = this ate dynamic contents that interact with database. ent ete. swith popular databases like MySQL PUP is basically used for PUP is open source - postyreSQL., Oracle ete developing web apps Why PHP? PHP runs on different OS platforms like © Windows (WAMP) © Linux (LAMP) © MAC OS (MAMP) PHP is an interpreted language, PHP ‘5 compatible with almost all servers but the most used server is apache. PUP is open source so it is free to download and use PHP is easy to use and widely used. Characteristics of PHP. © Efficiency © Securi © Flexibility © Familiarity Who are using PHP? Many reputed domains are using PHP Facebook Yahoo Wikipedia WordPress (0+ million other domains are using PHP History of PHP Versions: PHP /FI 1.0 released in 1995 PHP /FI 2.0 released in 1997 PHP 3.0 released in 1998 PHP 4.0 released in 2000 PLP 5.0 released in 2004 PHP 5.3 released in 2009 PHP 7.0 released in 2014 eee reese PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 1 fdvantsees Lely and free from cost. Itean be nt advantage of PIP is that it's open source eine ‘cb applications. downloaded ny where and readily available to use for web appli © It is platform independent, PHP based application Linux and Windows. ete , © Application can easily be Hoaded which are based on PHP Is mainly used due to its faster rate of loading ove! programming language. I has less leaming curv familiar with C programming can easily work on PHP. because it is simple and straightforward to use. ns can run on any OS like UNIX, and connected to database, 1 slow internet speed than another Someone © [vis more stable from a few years with assistance of providing continuous support to Various versions, ions. sophisticated structure for event of web appli © Ihelps in managing code easily. It helps in reusing an equivalent code and no got to write lengthy code and + It has powerful library support to use various function modules for data representation, PHP's built-in database connection modules help in connect trouble and time for development of web applications and content based may be potential candidates for hire. 1g database easily reduce S. Popularity of PHP gave rise to various community of developers, a fraction of which Flexibility makes PHP ready to effectively combine with many other programming languages in order that the software package could use foremost effective technology for every particular feature Syntax of PHP: A PHD script can be placed anywhere in the document. A PHP script starts with <2php echo "Hello, World!"; > echo is a command used in PHP to display anything on sereen, Comment: /IAhis is single line comment # this is also single line comment /* this is multi tine comment, * can spread over thousands of lines */ PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 2 Des. may vary during the Variable is name given to memory location whose va execution of program Variables in a program are used to store some values or data that program. © Any ariables declared in PHP must begin with a dollar sign (S), followed by the variable name. * A variable can have long descriptive names (like Sfactorial, Seven_nos) or short ames (like $n or $f or $x) * A variable name can only contain alphanumeric characters and underscores (ic. ‘az’. °A-Z°, “0-9 and *_’) in their name, Even it cannot start with a number, * Assignment of variables is done with the assignment operator, “equal to (=)". The Variable names are on the left of equal and the expression or values are to the right of the assignment operator * One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers, * PHD is a loosely typed language, and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values. The same happens while conversion. No variables are declared before they are used. It automatically converts types from one type to another whenever required. * PHP variables are case-sensitive, i.e. $sum and $SUM are treated differently. Constants * A constant is an identifier (name) for a simple value. The value cannot be changed during the script. * A valid constant name starts with a letter or underscore (no § sign before the constant name). yntar define(name, value, case-insensitive) example: <2php 1/ case-sensitive constant name define("GREETING”, "Welcome to Softanic!"); echo GREETING; > Variable Scopes Scope of a variable is defined as its extent in program within which it can be acy scope of a variable is the portion of the program within which it is visible or can be accessed. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 3 ssed, ie. the Depending on the scopes, PHP has three variable scopes + The variables declared within a function are function and have its scope only in that particular function. In accessed outside that function. Any declaration of @ variable outside the function with the same name as that of the one within the function is a completely different variable. We will learn about functions in detail in later articles. For now, consider a function as a block of statements Glob: These variables can be accessed directly outside a function. To x We need to use the “global” keyword before the variable to refer to the global variable, Statie variable: It is the characteristic of PHP to delete the variable, ones it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution, To do this we use static keyword and the variables are then called as static variables. PHP associates a data type depending on the value for the variable. =Iphp fanction static_var() { called local variables to that Local varia called local mple words, it cannot be ables: The variables declared outside a function are called global variables. access within a function JI static variable static $num = 5; Ssum = 2: Ssum++; Snum++; // first function call static_var(); 17 second function call static_var(); > Output: aoe Datatypes © Data types specify the size and type of values that can be stored Variable does not need to be declared ITS DATA TYPE adding a value to it PHP is a Loosely Typed Language so here no need to define data type To check only data type use gettype( ) function. To check value, data type and size use var_dump( ) function, eee PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page 14 wee eevee vwnwe wee ve em emUUCUCU SGU] OST C CHE C CECE HE HH SH HE * Doubles NULL. Strings Booleans Arrays Objects ® Resources Expressions and operators Operators are symbols that tell the PHP processor to perform certain actions. For example, the addition (+) symbol is an operator that tells PHP to add two variables or values, while the greater-than (>) symbol is an operator that tells PHP to compare two values. The following lists describe the different operators used in PHP. PHP Arithmetic Operators The arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Here's a complete list of PHP's arithmetic operators: Operator Description Example Result + Addition Sx+Sy Sum of Sx and Sy 7 Subtraction Sx-Sy Difference of $x and Sy. . Multiplication $x * Sy Product of Sx and Sy. 1 sion Sx/$y Quotient of $x and Sy % Modulus Sx %Sy____ Remainder of Sx divided by Sy Example: “en"> Je>PHP Arithmetic Operators "; echo(Sx - $y); echo "
" echo(Sx * Sy); PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page |5 echo "ebro" echo($x / Sy): chol$x % Output 4 PHP Assignment Operators The PHP assignment operators are used with numeric values (0 write a value to a variable, The basic assignment operator in PHP is" value of the assignment expression on the right. tor Deseription = Assign Add and assign = Subtract and assign = Multiply and assign = Divide and assign quotient % Divide and assign modulus Example: ". It means that the left operand gets set to the Is The Same As Sx = Sy Sx = $x + Sy Sx = $x - Sy Sx = Sx * Sy Sx = $x / Sy $x = Sx % Sy PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 6 hut fang= "en" head title “PHP Assignment Operators: title Mead ": Sx = 20; Sx += 20: echo Sx: echo "
": Sx = 50; Sx-= 20; echo S: echo "
"; $x=5: Sx *= 25; echo $x; echo "
"; $x = 50; Output: 125 5 lo PHP Comparison Operators The PHP comparison operators are used to compare two values (number or string): Operator Name Example Equal Result True if $x is equal to Sy PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 7 = Mdentical : Not equal Not equal == Not identical < Less than > Greater than Greater than or equal to Less than or equal to him! lang="en"> title» PHP Comparison Operators "; var_dump($x != $y); echo "
", var_dump($x != $2); echo "
"; var_dump(Sx < $y): echo "
", var_dump(Sx > $y); echo "
", var_dump($x echo "
" var_dump(Sx > $2); y): = $y}; Output: True if $y is equal to $y ang are of the same type th True if $x is not equal wy 5, True if $x is not equal iy §, True if $v is mot equal y 5 they are not ofthe same ype Truc if $x is less than y True if $x is ureater than sy True if $x is greater thay M1 OF ; to $y “ True if $x i less than oF equa y sy : t ¢ PHP@Info_Planet Compiled by: Prasad Neve 8275331362 Page | 8 bool(true) bool( false) boolttrue) bool(true) bool(true) bool( false) bool(true) bool(false) PHP Incrementing and Decrementing Operators The increment/decrement operators are used to increment/decrement a variable's value. Operator Name 48x Pre-increment Sx Post-increment ~Sx Pre-decrement $x-- Post-decrement Example: Effect Increments $x by one, then returns $x Returs $x, then increments $x by one Decrements $x by one, then returns $x Retums $x, then decrements $x by one = IDOCTYPE html Junil tans itle> PHP Incrememing and Decrementing Operatorsstitle> ", echo Sx echo "hr": sxe 10, echo Sx~* echo "
": echo Sx; echo "
": Sx = 10: echo Sx, echo "br", PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 9 9 9 10 9 PHP Logical Operators The logical operators are typically used to combine conditional statements. Operator Name Example — Result and And Sxand Sy True if both $x and Sy are true or Or SxorSy True if either $x or Sy is true xor Xor Sxxor Sy Truc if either $x or Sy is true, but not both && And Sx && Sy True if both $x and Sy are true il Or __SxIISy_Truc if either SSx or Sy is rue ee Not Sx True if $x is not true Example: htm! lang="en"> PHP Logical Operators <2php PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 10 Syear = 2014: Leap years are divisible by 400 of by 4 but not 100 iN(Syear % 400 == 0) || (Sycar % 100 I= 0) && (Syear % 4 == 0)))5 echo "Syear isa } else} echo "$year is not a leap y bbody> Output: 2014 is not a leap year. PHP String Operators There are two operators which are specifically designed for strings. Operator Description Example Result Coneatenation Ssirl. $str2__ Concatenation of $strl and Sstr2 ample: Concatenation assignment $strl = $str2 _Appends the Sstr2 to the Sstr! PHP String Operators echo $x . Sy;// Outputs: Hello World! echo "
"; Sx = Sy; echo $x; // Outputs: Hello World!
Output: Hello World! Hello World! PHP@Info Planet Compiled by: Prasad Neve - 8275331362 Page [11 PUP Arr, y Operators Operato Name Example Result r «| + Union sy + $y Union of $x and Sy Pll Equality sy ‘True if $x and Sy have the same key/value pairs | Identity. True if Sx and Sy have the same key/value pairs ‘| in the same order and of the same types, 7 Inequality $x != Sy True iF $x is not equal to Sy a = Inequality Sx <> sy True if $x is not equal to Sy el Non-identi $x !== $y True if $x is not identical to Sy y 7 € & & 4 4 ‘ The array operators are used to compare arrays: Example: ‘ <PHP Array Operators > "Red", > "Yellow", "v" => "Orang Sx + Sy;// Union of Sx and Sy var_dump(S2); "Green", "e > "Blue"); "Pink"; PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 12 var_dump(Ss === Sy): echo "
" var_dump(Sx != Sy); echo “
”: var_dump(sx © Sy ee var_dump(Sx !== Sy): Outpu bool false) bool( false) bool(true) bool(true) bool(true) string(S) “Green” ["e"]=> string(4) “Blue” string(4) "Pink" j PHP@info_Planet Compiled /: Prasad Neve - 8275331362 Page | 13 Uy S tue cit tegen jerent Conditional statements are used to perform dif em In PHP we have the following conditional sta eee ein ie © if statement - executes some cod ta condition is xecutes some code i © ifelse statement ~ if that condition is es different © © if.elseif. else statement ~ executes differ conditions Pare ate switch statement - selects one of many block: if Statement ion is true. The if statement executes some code if one condition is tr Syntax: tions based on difle mnt conditions rel true and another code des for more than two executed if (condition) { code to be executed if condition is true: Example: <2php St=date("H"); if (St <"20") { echo "Have a good day Output: Have a good day! f...else Statement The if...clse statement executes some code if a condition is condition is false Syntax: true and another code that if (condition) { code to be executed if condition is true: Jelse { code to be executed if condition is false; J Example: PHP@Iinfo_Planet Compiled by: Prasad Neve - 827533 a6 Page | 14 body php St da if (St < "20" { echo “Have a good day!": Jelse echo "Have a good night!"; “Mody Output Have a good day! if...elseif., The if, Syntax: Ise Statement elseif...clse statement executes different codes for more than two conditions. if (condition) { code to be executed if this condition is true; } elseif (condition) { code to be executed if first condition is false and this conditi J else { code to be executed if.all conditions are false; Example: jate("H");, echo "

The hour (of the server) is". $t; echo", and will give the following message:

* if(St<"10") { echo "Have a good morning!"; } elseif ($t.<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } > Output PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 15 switeh The sw Syntax: The hour ot the server) is 10, and will give the fallowing messa ood day! h Statement switch (n) { case label code to be executed if n=labell: break: case label2: code to be executed if n=label2: break: case label3: code to be executed if n=label3; break; default: code to be executed if n is different from all labels; } itch statement is used to perform different actions based on different com ions, Example: OCTYPE himi> PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 16 hut Output ae Your favorite color is red! break § Sometimes a situation arises wher atement we want to exit from a loop immediately w out waiting to get back to the conditional statement. The keyword break ends execution of the current for, foreach, while, do while or switch structure. When the keyword break executed inside a loop the control automatically passes to the first statement outside the loop. A break is usually associated with the i Examp! 1500) echo Ssum; > Output 1800 continue Statement Sometimes a situation arises where we want to take the control to the beginning of the loop (for example for, while, do while etc.) skipping the rest statements inside the loop which have not yet been executed, The keyword continue allow us to do this. When the keyword continue executed inside a loop the control automatically passes to the beginning of loop. Continue is usually associated with the if. Example: =2php Sw echo ‘List of odd numbers between 1 to 10
': while ($x<=10) t if (Sx % 2} 0) PHP@Info_Planet ‘Compiled by: Prasad Neve - 8275331362 Page | 17 Se continue, che Save ceho $x."ebr Output 1 3 5 7 9 List of odd numbers between | t0 10 PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 18 Loop control structure 1e block the sa Loops are used to ain, as long a5 a certain condition is true. In PHP, wwe have the following loop types: © while - loops through a block of code as long as the specified condition is true © do..while - loops through a black of code once, and t repeats the loop as Jong as the specified 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 while Loop The while loop executes a block of code as long as the specified condition is true. Syntax: while (condition is true) { code to be executed; Examples: php Sx= 1: while(Sx <= 5) { echo “The number is: $x
"; Sixt: Output: ‘The number i The numbe The number i The numbe The number is. Do while Loop The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax: do{ code to be executed; } while (condition is true); Examples: "; PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 19 Output The number is: The number is: ‘The number is: The number is: The number 4 5 for Loop The for loop is used when you know in advance how many times the script should run Syntax: for (init counter; test counter; increment counter) { code 10 be executed for each iteration; } Parameters © init counter: Initialize the loop counter value * fest counter: Evaluated for each loop iteration. If it evaluates to TRU! loop continues. IFit evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value the Example: <2php for (Sx = 0; $x <= 10; Sx+4) { echo "The numbei $x
"; i Output: The number is: 0 The number is: ‘The number is: 2 ‘The number The number is: 4 The number ‘The number is: 6 ‘The number is: 7 ‘The number is: 8 The number is: 9 PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 20 Fo array synteny, ch Loop The foreach loop works only on arrays, and is used to loop through each key/v foreach (Sarray as $value) code to be executed; le: php Scolors = array("red' "blu "grec foreach (Scolors as $value) echo "Svalue
": Output: red green blue yellow PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 21 inctions & Graphics ting and manipulating arr Arrays in PHP is a type of data structure that allows us to store multiple elem data type under a single variable thereby saving us the effort of creating a different variable clpful to create a list of elements of similar types. which can ents of similar for every data, The arrays Suppose we want to store five names and print them .¢ different string variables. But if be accessed using their index or ke accordingly, This can be easily done by the use of instead of five, the number rises to a hundred, then it would be really difficult for the user or developer to create so many different variables. Here array comes into play and helps us to nt within a single Variable and also allows easy access using an index or a store every ele key. An array is ereated using an array() function in PHP. There are basically three types of arrays in PHP: Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key Multidimensional Arrays: An array w can be accessed via multiple indices yy within it and ich contains single or multiple at Indexed or Numeric Arrays These type of arrays can be used to store any type of elements, but an index is always a number. By default, the index starts at zero, These arrays can be created in two different ways as shown in the following example: hp One way to create an indexed array Sname_one = “Anthony”, "Ram", im”, "Raghav"; Accessing the elements directly. echo "Accessing the Ist array elements directly:\n"; cho Sname_one[2}, “in” ‘ho Sname_one| 0). “\n echo Sname_one[}, "In": ‘cond way to create an indexed array Sname_two[0] = "ZACK": Sname_two[1] = "ANTHONY ne_two[2] = "RAM": Sname_two[3] = "SALIM": Sname_two[4] = "RAGHAV’ #/ Accessing the elements directly echo "Accessing the 2nd array elements directly:\n”: echo Sname_two[2}, "\n": echo Sname_two[0]. "\n"; echo Sname_twol4]. "Wn" PHP@into_Planet Compiled by: Prasad Neve - 8275331362 Page | 22 Output Accessing the Ista Ram Zack R elements directly haw Accessing the 2nd array elements direetly RAM ZACK RAGHAV, ‘Traversing: We can traverse an indexed array using loops in PHP, We can loop through the indexed array in two ways. First by using for loop and secondly by using foreach. You can refer to PHP | Loops for the syntax and basic use. <2php // Creating an indexed array Sname_one = array("Zack". "Anthony", "Ram! // One way of Looping through an array using foreach echo "Looping using foreach: \n foreach (Sname_one as $val){ echo Sval. "\n" 17 count() function is used to count J/ the number of elements in an array Sround = count(Sname_one); echo "\nThe number of elements are $round \n"; 1/ Another way to loop through the array using for echo "Looping using for: \n"; for($n = 0; $n < Sround; $n++){ echo Sname_one{Sn}. "\n"; } P Associative Arrays These types of arrays are similar to the indexed arrays but instead of linear storag value can be assigned with a user-defined key of string type. "Sara", “Raghay"=>"Ravina’”) Second way to ereate an associative array Sname_wvof"zack"] = "zara": Sname_two["anthony"] Sname_two| echo “Accessing the elements directly:\n": echo Sname_two["zack"], "\n": echo Sname_twof"salim” echo Sname_two["anthony"], "\n"; echo Sname_one["Ram"], "\ echo Sname_one["Raghav"], > Accessing the elements directly: zara sara any Rani Ravina rsing Associative Arrays: We can traverse associative arrays in a similar way did in ‘ic arrays using loops. We can loop through the associative array in two ways. First by for loop and secondly by using foreach. You can refer to PHP | Loops for the syrtax sic uses Example: "Zara", "Anthony"=>"Any", "Ram "Raghav" // Looping through an array using foreach echo "Looping using foreach: \n"; foreach (Sname_one as $val => Sval_value){ echo "Husband is ".$val PHP@Info_Planet ‘Compiled by: Prasad Neve - 8275331362 Page | 24 Looping through an array using for echo “aL ooping using for: n" Sheys ~ array_heys(Sname_ two), Sround ~ count(Sname_two). for($i-0, Si < Sround: +*Si) { echo Skeys[Si] ."'. Sname_two[SkeysfSi]]." Output Tooping using foreach: Husband is Zack and Wife is Zara Husband is Anthony and Wife is Any Husband is Ram and Wife is Rani Hushand is Salim and Wife is Sara Husband is Raghav and Wife is Ravina Loopi sing for: zack zara anthony any ram rani salim sara Multidimensional Arrays Multidimensional arrays are such arrays that store another array at each index instead of single element. In other words, we can define multi-dimensional arrays as an array of arr As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within, Arrays or sub-arrays using multiple dimensions, Example: "Dave Punk’ “mob” => "5689741523 ‘email => “[email protected]”, d array( nam Monty Smith", "mob" => "2584369721 “email” => "[email protected]*, multidimensional arrays can be accessed PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 25 array( “name” => "John Flinch”, "mob" =» "9875147536" “email” Accessing elements echo "Dave Punk email-id is: ". $favorites[O]f"email"]. "\n"; echo “John Flinch mobile number is: " . Sfavorites{2]]"mob’ Output: Dave Punk email-id is: [email protected] John Flinch mobile number is: 9875147536 Array functions 1. imploded PHP implode Function joins elements of an array into a single string. It returns a string containing elements of the array. Syntax: implode(Sdelimiter , Sarray ); PHP implode Function expects two parameters. One parameter is mandatory while the other is optional. However, it accepts the parameters in cither order. > Sdelimiter: Delimiter or the separator is an optional parameter and specifies by what character the array elements will be joined. The default value of delimiter is an empty string. > Saray: Sarray is an array of strings to implode. It is a mandatory parameter. Return Value: PHP implode Function returns a string from the elements of the array separated by the given delimiter, Ex. implode(™, array(How, ‘Are’ 'You?); Output: How-Are-You? implode(’’. array(apple’, ‘mango’, banana’), Output: apple,mango,banana PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 26 2. Exploded) PHP explode Function is an inbuilt strin b an array containing exploded sub-strings of the string. Sub-strings form by split function of PHP. Explode literally means to cak down, The Function splits or bre a string into an array of strings. It returns, the string by given string delimiter. Syntax explode(Sdelimiter, $string): Pa PHP Explode Function expects two mandatory parameters and one optional rameters parameter. The description of the parameters is as follows: > Suelimiter: Delimiter or the separator is the mandatory parameter. It specifies Where to break the string from. The function will split the string around the delimiter. > Sstring: Original string on which explode operation is to be performed. It is also a ‘mandatory parameter Return Value PHP Explode Function retums an array containing the sub-strings of the string exploded. Moreover, the return values also depend upon the limit passed. =2php Sstring SexplodedString = explode(’ print_1(SexplodedString); -how-are-you-doing? Sstring); Output ‘Array ( [0] >Hi [1] => how [2]=> are B) => you [4] > doing? ) 3. Array_flip) The PHP array_flip Function is an inbuilt function in PHP which exchanges the keys with their values in the associative array. It returns an array with the corresponding keys and values exchanged. However, the values of the existing array should be valid keys ie. either string or integer. The function throws a warning if the new keys are not valid. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 27 used as its value, and all If a value has several occurrences, the latest hey will be others will be Lost Syntax: array array_lip(array meter in the array Nip Function, The pa Parameter is only one par should be an array whose keys and values are to be exehanged Return Type: The PHP array_flip Function returns an array with the Keys and values exchanged However, it returns a NULL value if the input va Ey <2php Sinput = array(“oranges". "apples". " SMlipped = array_Mip(Sinput): print_s(SMipped); Output: Array ( {oranges} => 0 [apples] => 1 pears] => 2 ) Array_push() PHP array_push Function is an inbuilt function in PHP which inserts new elements in an array. It always inserts elements at the end of the array. The count of the array is also incremented by one. Moreover, multiple elements can be passed in the array_push function at once. Syntax: array_push(Sarray, Svall, Sval2, Sval3 . Parameters: We can pass multiple parameters in the PHP array_push Function. It depends on the number of elements we want to add at once. Let’s consider two types of categories of elements that can be passed: > Sarray: The first parameter is a mandatory array. The PHP array_push Function inserts new elements in this input array. An empty array can also be passed as the first parameter. > SelementList: The second parameter is the comma-separated element list we Want to add to array in PHP. Return Value: ‘The function returns the modified array with all the elements inserted at the end. Note: The PHP array_push method always adds a new numeric key in the original array even if the array has string keys. Example: PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 28 PHP@Info_Planet ‘Compiled by: Pr StestArray = array() array _push(StestArray. 1; print_r(StestArray), Ary (i [o}=> 1 ) array_push(StestArray, ‘Concatly'); print_r(StestArray): Ir Array « [o]=>1 [1] => Concatly ) 7 array_push(StestArray, array(‘John’, 'Doe’)); print_r(StestArray); r Array ( [o)=>1 [1] => Concatly (2) => Array ( [0] => John [1] => Doe ) ) ” > array_pop() PHP array_pop Function is an inbuilt function in PHP which removes the Inst element from an array. It returns the last ‘value of the array. Also, it decrements the size of the unay by one. PHP array_pop Funetion works opposite to array_push function, “Syntax: array_pop ( array Sarray Ji Parameters: Pat? array. pop Function takes in only one parameter. The required array from which the element needs to be removed. PHP array_pop Function throws If you don't pass any parameter, y. However, it does not throw any warning/notice on passing an empty arr Return Value: The function returns the last element from the array. Ifthe array is empty, then it returns NULL 1 is removed 11 of the array. The returned elem: rasad Neve - 8275331362 Page | 29 orange [1] = banana [2]=> apple ) 6. count()/ sizeof() The count Function in PHP is one of the most used inbuilt functions. It returns the count of elements in an array in PHP. In this article, we will discuss the PHP count Function, PHP sizeof Function is an alias of the count function Syntax: integer count(Sarray, $mode = 0); Parameters: The PHP count Function expects two parameters. One parameter is mandatory while the other is optional, The description of the parameters is given below: > Sarray: The first parameter is a mandatory array for which you require to count elements. Also, you can pass a multi-dimensional array to it ¥ Smode: The second parameter to the PHP count is the mode. It is an optional parameter with the default value as 0. It can have two possible values: 0— Default. Does not count all elements of multi-dimensional arrays. 1 = Counts the array recursively (counts all elements of a multi-dimensional array). 7. sort() PHP sort is an inbuilt function in PHP. It sorts an array in ascending order smaller to bigger element. Also, it makes the changes in the original array itself. from Syntax: boolean sort(Sarray) Return Value: The PHP sort Function returns true on success and false on failure. However, it modifies the original input array. Note: The function assigns new keys to the elements in the array. It will remove any xisting keys rather than re-ordering. Example <2php Sarray = array(5, 1, 2, 7, 3); sort(Sarray); print_r(Sarray); Compiled by: Prasad Neve - 8275331362 Page | 30 PHP@Info_Planet 8. rsort() PHP rsort is an inbuilt function bigger to smaller element. Also, it makes the changes in the original a PHP. It sorts an array in descending order i.e. from ay itself. Syntax: boolean rsort($array) Return Value: ‘The PHP rsort Function returns true on success an modifies the original input array. \d false on failure. However, it Note: The function assigns new keys to the elements in the array. It will remove any existing keys rather than re-ordering Example: <2php Sarray = array(5, 1, 2, 7,3); rsort(Sarray); print_r(Sarray): i Array ” 2 9, asort0) : - PHP asort is an inbuilt Function in PHP. It sorts arrays in ascending order while reaining the relationship between Keys and values. The smallest element in the input array appears first and the largest appears ast Note: This function is mostly helpful in sorting Associative Arrays because the because it preserves the relation between keys and values Syntax: bool asort( Sarray ) Example: <2php 362 Page | 31 PHP@Info_Planet Compiled by: Prasad Neve - 8275331 ‘a => ‘apple’ Sarray © array(b’ asont(Sarray): print_rSarray): Array ( [a] => apple [b] => banana Ic] => cat 1 10. arsort() ; PHP arsort is an inbuilt Function in PHP. It sorts arrays in descending order while maintaining the relationship between keys and values. The smallest clement in the input array appears first and the largest appears last, Note: This function is mostly helpful in sorting Associative Arrays because the because it preserves the relation between keys and values. Syntax: bool arson Sarray ) Example: <2php Sarray = array(5, 1,2, 7. 3); arsort(Sarray print_e(Sarray); U?Keys are preserved 1. ksort() PHP ksort is an inbuilt Function in PHP. It sorts arrays in ascending order according to keys while maintaining the relationship between keys and values. The smallest key in the input array appears first and the largest appears last. Syntax: bool ksort( Sarray) Example: “<2php StestArray = array( => 5, 0=> 6,4 => 3,3 => 2,2=> 1); ksort(StestArray); print_r(StestArray); PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 32 12. krsort() PHP krsort is an inbt to keys while maintaining the relationship between key’ and value: in the input array appears last and the largest appears first. It Function in PHP. It sorts arrays in descending order according The smallest key mntax: bool krsort( Saray) Ex. <2php StestArray = array(1 => 5, 0 => 6, 4 = krsort(StestArray); print_r(StestArray); r Array ( eS 13, in_array) ‘The in_array Funetion is an inbuilt Function in PHP. It is used to check whether an element exists in an array or not. It is one of the most used functions in PHP. Syntax: bool in_array (Sneedle, Shaystack, SstrictMode = false) Parameters: ‘The PHP in_array Function takes in three parameters. Two parameters are mandatory and one is optional. Let's discuss about the parameters below: > Sneedle: The needle is the first parameter function to the function. It is a mandatory parameter and specifies the element to be searched in the given array. ‘Also, the needle can be an integer, string and even array. > Shaystack: The haystack is also a mandatory parameter. It is the array in which to search. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 33 ameter It > SstrietMode: The third parameter to the function is an optional pa specifies whether the search will be striet or not. [the parameter ty true then the function matches the value and type of the elements, However, the default value of the parameter is false Return Value: The PHP h Function returns a boolean value. If the needle is present in the _array ystack, then it returns true. Otherwise, it returns false. Example: php Shaystack = array(5. 0.6, 21, 63, 24): _dump(in_array(6, Shaystack)); /* bool(truc) */ var_dump(in_array(1, Shaystack)); /* bool(false) */ 14, array_merge() PHP array_merge Function is an inbuilt Function in PHP which merges two or more arrays, This function merges elements in two or more arrays into one single array. While merging. it appends the elements of an array at the end of the previous array Syntax: array array_merge(Sarray 1, Sarray2, . Sarrayn) ‘The PHP array_merge Function takes in a list of array parameters. You can pass any number of parameters in the function. However, all the parameters must be arrays. If the input arrays contain the same numeric keys, then the PHP array_merge will append the keys and not overwrite them. However, if the arrays contain the same string keys then it overwrites the later value of the keys with the previous one. Return Value: The PHP array_merge Function in PHP returns a single array after merging the arrays passed in the parameters. Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array Example: <2php Sarray 1 = array(13,5); Sarray2 = array(2.4,6); ‘SmergedArray = array_merge(Sarray l, Sarray2); print_r(SmergedArray), , ourPur Array PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 34 PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 35 eectensinc ice eae) ea sk. This block 11 alphabet or \ function is a reusable block of statements that performs a specific en a name that starts with a anywhere within the program any number of is defined with function keyword and is underscore. This function may be called from times am. © A function is a block of statements that ean be used repeatedly in a pr tically when a page loads not execute autom © A function © A function will be executed by a call to the function. According to author of functions there are two types of functions: 1. Built in funetions 2. User define finetions User define functions Function whose definition is defined by user is called as user define A user-defined function declaration starts with the word funet function fimsetionName() { code to be executed: function. functionName(); // function call Rules for function name: > Function name must start with letter or underscore or underscore( _ ) > Function name cannot start with number or any other special symbol followed by any number, letter > Function names are not case sensitive. > NOTE: You must give function name that shows the working of function Built in Functions Built in functions are functions who are already provided by PHP. The real power of php comes from its functions. PHP has more than 1000 functions. Ex. Echo(), print(), strlen(). print_r() User define or built in functions may have parameters According to parameters there are again two types of functions 1. Parameterized functions Functions who require parameters are called as parameterized function Ex. Function welcome(Suser) { Echo “welcome ”.Suser; } Welcome( Prasad’); Accordit © Pass by Value: On passing arguments using pass by value, the value of the argument gets changed within a function, but the original value outside the g to argument passed there are two types of functions PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 36 function remains unchanged, That meany a duplicate of the original val ate of the original value i passed as an argument ‘ Pass by Referenc Sn passing arguments as pass by reference, the ori cts altered. In pass by value is passed. Therefore, the original value fre we actually pass the address of the value, where it is stored using ampersand sin (&). + EX Function add5(&Sno) 1 Sno +=5; Echo “Before function call Add5(Sn): Echo “After function call = $n"; output 1/ Before function call = 10 / After function call = 15 2. Non parameterized functions Non parameterized functions don’t require any parameter (arguments) n welcome() t Echo ‘welcome user"; } Welcome(); falue, One funetion can have one or more I be executed at a function call. Functions may or may not return some return statements but only one statement ¥ Functions with default values PHP allows us to set default argument values for argument for a parameter with default value then PHP will function parameters. If we do not pass any use the default set value for this parameter in the function call. Ex. <2php function hello(Sname, Snum=12) t echo "$name is $num years old \n"; } 1/ Calling the function hello("Ram", 15); //In this call, the default value 12 1/ will be considered PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 37 hello" Adam"), alue 12. if we do not pass any value Inthe luc 12 will be considered. Also the er Snum has a default ¥ hove example, the parame for this parameter in a function call then this default val Parameter Sname has no default value . so itis compulsory iable functions. I the name of a variable has parentheses (with oF without parameters in it) in front of it, PHP ae sponds to the value of the variable and ida funetion whose name corre: 4 This feature is useful in eda variable function eXccutes it, Such a funetion is ca implementing callbacks ete. php function hello echo “Hello World": Svar="Hello"; Svar(); Anonymous functions Anonymous funetion is a function without any user defined nam: called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an anonymous function which closes over the environment in which it is defined. e. Such a function is also Syntax: ‘Svar=function (Sargl, Sarg2) { return Sval; }: There is no function name between the function keyword and the opening parenthesis. ¢ There is a semicolon afier the function definition because anonymous function definit “ Functi “When passed to another fun jons are expressions n is assigned to a variable, and called later using the variable’s name. \n that can then call it later, it is known as a callback. Some built in functions strlen() The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters. strlen(Sstring); Parameters: The strlen() function accepts only one parameter $string which is mandatory. This parameter represents the string whose length is needed to be returned. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 38 FIFDI®®AAAARHH HHH MRHRAARAHARAAAAHOC CAAA | 6©6C6CeCeCeoveseueseee ee eeweeaeee voeoeuveeeevee . The function returns the length of the Ssteing including all the and special characters. whitespaces strlen() function in PHP. Example 1: The below example demonstrates the use of tl ee "php 1/ PHP program to find the i ength ofa given string 1/ prints the // including the space echo strlen(Sstr);, Output: B 2. str_word_count() The str_word_count() functi information about words used in a string like total number word in the string is a built-in function in PHP and is used to retum positions of the words in the string ete. syntax: str_word_count ( $string , SretunVal, Schars ) Parameters Used: > Sstring:This parameter specifies the string whose words the user intends 10 count. This is not an optional parameter. } SreturnVal:The retum value of st_word_count() function is specified by the SreturnVal parameter. It is an optional parameter and its default value is 0. ‘The parameter can take below values as required: 0 -It returns the number of words in the string Sstrin 1 sft returns an array containing all of the words wi 2 :lt returns an associative array with key-value pairs, where the key deifies the position of the word in the string and the value is the word itself. h are found in the string, > Schars: This is an optional parameter which specifies a list of additional characters which shall be considered as a ‘word’. Return Type: The return type of function depends on the parameter SretumVal and return the values as described above. PHP@info_Planet ‘Compiled by: Prasad Neve - 8275331362 Page | 39 ctor Below programs explain the working of str_word_count() [i php Smystring = "Twinkle twinkle little star” Print_r(str_word_count(Smystring)): Output: 3. strrev() Reversing a string is one of the most basic string operations and is us d very frequently by developers and programmers. PHP comes with a built-in function to reverse strings The strrev() function is a built-in function in PHP and is used to reverse a string. This function does not make any change in the original string passed to it as a parameter. Syntax: String strrev(SinpString) Parameter: This function accepts a single parameter SinpString. This parameter is a string and it specifies the string which we want to reverse. Ifa number is passed to it instead of a string, it will also reverse that number. Return Value: The strrev() function returns the reversed string or the number. It does not make any change to the original string or number passed in the parameter. Examples: Input : Sstring = "geeks" Output : skeeg, Input : $string = 143 Output : 341 4. strops() This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently. Syntax: strpos(original_str, search_str, start_pos): PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 40 ter value: Out of the three parameters specified in the syntax, two are ndatory and one is optional. The three parameters are described below str: This is a mandatory parameter that refers to the or al string in > origi which we need to search the occurrence of the required string, > seareh_str: This is a mandatory parameter that refers to the string that we need to search > start_pos: This is an optional parameter that refers to the position of the string from where the search must begin. Return Type: This function returns an integer value that represents the index of al_str where the string search_str first occurs. orig 5. str_replace() The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively. Synt ‘SsubjectVal, Scount ) ‘str_replace ( SsearchVal, SreplaceVa Parameters: This function accepts 4 parameters out of which 3 are mandatory and | is optional. All of these parameters are described below: > SsearchVal: This parameter can be of both string and array types. This parameter specifies the string to be searched and replaced > SreplaceVal: This parameter can be of both string and array types. This parameter specifies the string with which we want to replace the $search Val string. > SsubjectVal: This parameter can be of both string and array types. This parameter specifies the string or array of strings which we want to search for SsearchVal and replace with Sreplace Val. > $count: This parameter is optional and if passed, its value will be set to the total number of replacement operations performed on the string SsubjectVal Return Value: This function returns a string or an array based on the SsubjectVal parameter with replaced values. 6. uefirst() The ucfirst() funetion is a built-in function in PHP which takes a string as an argument and returns the string with the first character in Upper Case and all other characters remain unchanged. Syntax: ucfirst(Sstring) Parameter: The function accepts only one parameter $string which is mandatory. This parameter represents the string whose first character will be changed to uppercase. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 41 The function returns the same string only by changing the first ssed argument Sstrin; se of the words) efi The ucwords() function is a buill-in function in PHP and is used to convert the first character of every word in a string to upper-case. Syntay: string uewords ( Sstring. Sseparator ) ers out of which first is compulsory Parameter: This function accepts two param; and second is optional, Both of the parameters are explained below: > Sstring: This is the input string of which you want to convert the first character of every word to uppercase. > Sseparator: This is an optional parameter. This parameter specifies a character Which will be used as a separator for the words in the input string, For example, if the separator character is ‘|’ and the input string is “Hellojworld” then it means that the string contains two words “Hello” and “world”. Return value: This function returns a string with the first character of every word in uppercase. 8. strtolower() The strtolower() function is used to convert a string into lowercase. This function takes a string as parameter and converts all the uppercase english alphabets present in the string to lowercase. All other numeric characters or special characters in the string remains unchanged. Syntax: string strtolower( Sstring ) Parameter: The only parameter to this function is a string that is to be converted to lower case. Return value: This function returns a string in which all the alphabets are lower case. 9.. strtoupper() The strtoupper() function is used to convert a string into uppercase. This function takes a string as a parameter and converts all the lowercase english alphabets present in the string to uppercase. All other numeric characters or special characters in the string remain unchanged. Syntax: string strtoupper ( $string ) Parameter: The only parameter to this function is a string that is to be converted to uppercase Return value: This function returns a string in which all the alphabets are uppercase. PHP@info_Planet Compiled by: Prasad Neve - 8275331362 Page | 42, 10, strempl) Comparing two strings is one of the most com and web development practices. The ly used string ; string operation in SIFEMPO ts. an inbuilt function in is function is ease-sen: that capital and small casey will be treated difleres ae anim PHP and is used to compare two strings. T pro Hy. during com function compares two strings and tells us whether the first string ism th est stein is ge than the second string or equ or smaller I 10 the second string Stremp(Sstring |. Sstring2) 7 Parameters: This function accepts two parameters which are described below > $string] (mandatory): This parameter refers to the first string to be used in the comparison Sstring2 (mandatory): This parameter refers to the second string to be used in the comparison, Return Values; The function returns a random integer value depending on the condition of match, which is given by: Returns 0 if the strings are equal. Returns a negative value (<0), if $string? is greater than Ssiring| Returns a positive value (>0) if Sstring! is greater than Sstring2. PHP@Info_Planet ‘Compiled by: Prasad Neve - 8275331362 Page | 43 teQ Function th C iMaxecreate This meee ‘0 function is an inbuilt function in PHP which is used to e1 ee a the blank image of given size. In g ‘on is used instead of r creates hi of imagecreate() function because imagecreatetruecolor() function h quality images, ynta imagecreate( Swidth, Sheight ) Paramet 8: This function a ;pIs tWo parameters as mentioned above and described below: y the image width. > Swidth: It is mandatory parameter which is used to spe ® Sheight: It is mandatory parameter which is used to specify the image height. Return Value: This function returns an image resource identifier on success, FALSE errors, imagecolorallocate() Function The imagecolorallocate() function is an inbuilt function in PHP which is used to set the color nan image, This function returns a color which is given in RGB format. Synt: int imagecolorallocate ( Simage, Sred, Sgreen, Sblue ) Parameters: This function accepts four parameters as mentioned above and described below > Simage: It is returned by one of the image creation functions, such imagecreatetruccolor(). It is used to create size of image. > $red: This parameter is used to set value of red color component. > Sgreen: This parameter is used to set value of green color component. > Sblue: This parameter is used to set value of blue color component. as Return Value: This function returns a color identifier on success or FALSE if the color allocation failed. imagestringQ Function The imagestring() function is an inbuilt function in PHP which is used to draw a string, Syntax: bool imagestring( Simage, $font, $x, Sy, Ssiring, Scolor ) Parameters: This function accepts six parameters as mentioned above and described below: > Simage: The imagecreate () function is used to create a blank image in a given size. > Sfont: This parameter is used to set the font size. Inbuilt font in latin? encoding can be I, 2, 3, 4,5 > Sx: This parameter is used to hold the x-coordinate of the upper left corner. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 44 yy This parameter is used to hold the y-coordinate of the upper let comer. > setring: This parameter is used to hold the string to be written ameter is used to hold the color of image. > Seolor: This para Return Value: This function returns True on suecess or False on failure imagerectangle() The imagercetangle() function is an inbuilt function in PHP which is used to draw the Pool imagerectangle( Simage, $x1, Syl, $x2, $y2, Scolor ) Parameters: This function accepts six parameters as mentioned above and described below: Simage: It is retumed by one of the image creation functions, such as ecreatetruccolor(). It is used to create size of image. + left x-coordinate v imag $x1: This parameter is used to set the uppe! Syl: This parameter is used to set the upper left y-coordinate $42: This parameter is used to set the bottom right x-coordinate, $)2: This parameter is used to set the bottom right y-coordinate. } Scolor: A color identifier created with imagecolorallocate(). v vv Return Value: This function returns True on success or False on failure. Note: we can use imagefilledrectangle(.Simage, Sxl, Sy1, $x2, Sy2- Scolor ) for filled rectangle imagepolygon() Function The imagepolygon() function is an in| ‘This function returns TRUE on success an used to draw a polygon built function in PHP whic! d returns FALSE otherwise, Syntaxt ‘bool Imagepolygon( Simage, Spoints, $num_points. Scolor ) bool imagefilledpolygon( Simage, Spoints, Sum_points, Scolor ) Parameters: This function accepts four parameters as mentioned above and described below: > simage: The imagecreatetruecolor() function is used to create a blank image ina given size. > Spoints: This parameter is used to hold the consecutive vertices of polygon > Snum_points: This parameter contains total number of vertices in a polygon. It must be greater then 3, because minimum three vertices required (o create a polygon. } Scolor: This variable contains the filled color identifier. A color identifier created with imagecolorallocate() function, PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 45 Return V Jue: This function returns TRUE on success or FALSE on failure. ple: php Create the size of image or blank image Simage = imageereate(500, 300); Set the vertices of polygon Svalues = array( 50, 50, // Point 1 (x. y) 50, 250, // Point 2 (x. y) 250, 50. // Point 3 (x. y) 250, 250 // Point 3 (x. y) y: Set the background color of image Sbackground_color = imagecolorallocate(Simage, 0, 153, 0): // Fill background with above selected color imagefill(Simage, 0. 0, Sbackground_color); // Allocate a color for the polygon Simage_color = imagecolorallocate(Simage, 255, 255, 255); // Punetion to create image which contains string. imagestring(Simage, 5, 180, 100, "GeeksforGeeks", Stext_color); // Draw the polygon imagepolygon(Simage, Svalues, 4, Simage_color); // Output the picture to the browser header(‘Content-type: image/png’); imagepny(Simage): a FS ET ee eee see 2 eee SS eee es as es es Creating PDF using PHP Download the {pdf library trom fpdf > Include fpdf_php file in your code in the library > Fpdf lass is defi Create new object of tpuf class like Spdf=new tpdt() You can pass few parameters to fpdf object Spdf=new Ipdi(“orientation init”, “size”): + Orientation: P of Portrait (default) .L or Landscape + unit: pt: point, mm: millimeter (default), em: centimeter, in: inch + size: A3, Ad(defaulty, AS, Letter, Legal or an array containing the width and the height (expressed in the unit given by unit) addPage() function Spdf->addPi rientation”,"size”,"rotation > Rotation value must be in multiple of 90; Setfont() function Spdf->SetFont(‘Arial’,’B',16); old italic © U=underline ° Cell function Cell(float w , float h , string txt , mixed border , int In, string align , boolean fill , mixed link) W= Width H= height Text is string to print Border: 0 no border / 1- border / L.-left / T-top/ R-right/ B-Bottom Ln: Indicates where the current position should go after the call. Possible values are 0: to the right / 1: to the beginning of the next line / 2: below © Align: L or empty string: left align (default value) / C: center / R: right align 0 Fill: | true/ 0— false Link: URL eo000 Output function string Output([string dest [, string name}]) > Dest: PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 47 © ks send the file inline to the browser. The PDF viewer is used if available, (default) © Ds send to the browser and force a file download with the name given by name. 6 F:save toa local file with the name given by name (may include a path), © S:return the documer asa string > name 0 The name of the file, The default value is doc.pdf. Other PDF functions % Spde>ing; This function is used to add new line in pdf file Spuf->SetTextColor(255,0,255); This function is used to set text color in pdf file © Spaf>Image("info.png", x position, y position, width, height); We can add images in pdf file using image function Spdf->Line(Moat x1, float y1, float x2, Moat y2) we can add line using this function Spdf->SetLineWidth(foat width) We can set custom width of lines using this function # Spdf->SetDrawColor(rgb); We can change color of lines using this function % Spaf>pageNo(; We can get page no of pdf file using this function PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 48 Oo ae PHP © the sun, earth, moon ete ent objects like wheels, ste ne our universe made of different objects, of diffe We can i Similarly we can imagine our ear made ing. ete nted programming concepts which assume everything as an Same way there is object ori in different objects. object and implement a softwar Object Oriented Concepts Refore we go in detail, let's define important terms related to Object Oriented Programming. > Class ~ This ch includes local functions as well as local data, You can think of a class as; a programmer-defined data type, whi template for making many instances of the same kind (or class) of objects. > Object — An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it, Objects are also known as instances. > Member Variable ~ These invisible to the outside of the variables are called attributes of the object one > Member function ~ These are the functions defined inside a class and are used to data will be an be accessed via member functions. These an object is created. re the variables defined inside a class. This class and access object data. > Inheritance ~ When a class is defined by inheriting the existing function of a class then it is called inheritance. Here a child class will inherit all or few member functions and variables of a parent class. arent class — A class that is inherited from another class. Thi rent is also called a base class or super class. > Child Class ~ A class that inherits from another class. This is also called a subclass or derived class. > Polymorphism ~ This i used for different purposes. For example, the function name will remai it takes a different number of arguments and can do different tasks. > Overloading — a type of polymorphism in which some or all of operators have ifferent implementations depending on the types of their arguments. Similarly an object oriented concept where the same function can be the same but functions can also be overloaded with different implementations > Data Abstraction ~ Any representation of data in which the implementation details are hidden (abstracted). > Encapsulation ~ refers to a concept where we encapsulate all the data and member functions together to form an object. > Constructor ~ refers to a special type of function which will be called automatically whenever there is an object formation from a class. > Destructor ~ refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope Class {A class isa template for objects, and an object is an instance of class. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 49 Jcfined by using the Elass keyword, fallowed by the name ofthe elass and a pair oF euty aces) AM ats Properties and methods go inside the braces, php class Fruit § code goes here. Example php class Fruit Properties Public Sname: Public Scolor; / Methods function set_name(Sname) { Sthis->name = Sname; } function get_name() { return Sthis->name; } fined in the class, but they will have different Property values Objects of a class is created usin Example: “php class Fruit { 1 Properties public Sname; public Scolor: ig the NEW keyword, / Methods function set_name(Sname) { Sthis->name = Sname; function get_name() { return Sti name; Sapple ~ new Fruit(), Sbanana = new Fruit(); Sapple~-set_name(‘Apple'; PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 50 core QR9oe rer eer fers @ a < eX Sa 2 Shanana--set_name(Banana’) echo Sapple- “get name) echo" br" ‘echo Shanana~-get_name() Outpu Apple Banana, Constructor A constructor allows you to initialize an object's properties upon creation of the object. wy a __construct() function, PHP will automatically call this function when you crea an object from a class. Notice that the construct function starts wit ate th two underscores (_)! Example’ name = Sname; Sthis->color = Scolors function } function get_name() { return Sthis->nami } function get_color() return Sthis-color; } Sapple = new Fruit(" Apple" echo Sappl yet_name()i Output Apple red Destructor ‘A destructor is called when the object IS desiructed or the script is stopped or exited 1, PHP will automatically call this function st the end of the f you create a__destruct() fun script. otgce thatthe destruct function stats with Wo underscores (_)! Exampl hp class Fruit { Compiled by: Prasad Neve 8275331362 Page | 51 PHP@Info_Planet public Sname: public Seok function __construct(Sname) { Sthis- name = Sname; ’ function _destruct() { echo "The fruit is {Sthis--name}.” Sapple new Fruit(*Apple") Output The fruit is Apple Access modifiers In the PHP each and every property of a class in must have one of three visibility levels, known as public, private, and protected. ‘ublie: Public properties can be accessed by any code, whether that code is inside or outside ° the class. Ifa property is declared public, its value can be read or changed from anywhere in your script. © Private: Private properties of a class can be accessed only by code inside the class. So if we create a property that's declared private, only methods and objects inside the same class can access its contents. © Protected: Protected class properties are a bit like private properties in that they can't be accessed by code outside the class, but there's one little difference in any class that inherits from the class i.e. base class can also access the properties. Generally speaking, it’s a good idea to avoid creating public properties wherever pos safer to create private properties, then to create methods that allow code outside the class to access those properties. This means that we can control exactly how our class's properties are accessed. Note: If we attempt to access the property outside the class, PHP generates a fatal error. PHP Access Specifier’s feasibility with Class, Sub Class and Outside World Te le. Instead, it’s ee (Roce Specifier Gries Ons te ‘Yes lo No Protected. ‘Yes es No Public ‘Yes es Yes. Inheritance Inheritance is the way of extending the existing class functionality in the newly created class. We ean also add some additional functionality to the newly created class apart from extending the base class functionalities. When we inherit one class, we say an inherited class is a child class (sub class) and from which we inherit is called the parent class. The parent class is also known as the base class. This is the way that enables the better management of the programming code and code reusability. The idea behind using the inheritance is all about better management of the code and the code reusability. In this topic, we are going to learn about Inheritance in PHP. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword. PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 52 public Sname: public Seolor public function __construct(Sname, Scolor) { Sthis->name = Sname: Sthis->color = Scolor: public function intro) { echo "The fruit is { this->name} and the color is {Sthis->color}.”: Strawberry is inherited from Fruit class Strawberry extends Fruit { public function message() { echo "Am La fruit or a berry? Sstrawberry = new Strawberry("Straw berry", "red"); Sstrawberry->messa Sstrawberry-intro(): Function overloading and Overriding in PHP Function overloading and overriding is the OOPs feature in PHP. In funeti more than one funetion can have the same method signature but different number of se of function overriding, more than one functions will have same n overloading. arguments. But in ca method signature and number of arguments. Function Overloa Function overloading contains same function name and that function performs different task aecording to number of arguments For example, find the area of certain shapes where radius are given then it should give area of rectat overloading can not be done by native approach. In PHP all(). This function takes function name and arguments, are given then it should return area of circle if height and width ingle and others. Like other OOP languages function function overloading is done with the help of magic function _ function PHP program to expla overloading in PHP Creating a class of type shape class shape { call is magic function which accepts Function name and arguments area(2)) echo “in! calling area method for rectangle echo (Ss->area(4. 2)): Output: 6.28 8 Function Overriding: Function overriding is same as other OOPs programming languages. In function overriding, both parent and child classes should have same function name with and number of arguments. It ised to replace parent method in child class. The purpose of overriding is to change the behavior of parent class method. The: two methods with the same name and same parameter is called overriding. Example: <2php // PHP program to implement // fanction overriding, 1/ This is parent class class P { // Function geeks of parent class function geeks() { echo "Parent"; } i PHP @Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 54 This is child class class C extends P { / Overriding geeks method function geeks() { echo "\nChild’ i 1 Reference type of parent Sp = new P; 1/ Reference type of child $e= new C; 1/ print Parent Sp->gecks(): 11 Print child S$c->geeks(); > Output: Parent Child Object Cloning ‘An object copy is created by Using the clone keyword (which calls the object’s _elone() method if possible). An object's __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references. Syn ‘Scopy_object_name = clone Sobject_to_be_copied Ex. <2php 1/ Program to create copy of an object 1/ Creating class class GFG { public Sdatal; public Sdata2; public Sdata3; PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 55 ing object Sobj = new GEGOE Creating clone oF copy OF PIECE Scopy = clone Sobj Set values of Sobj object Sobj-~datal = "Geeks": Sobj->data2 = “for”: Sobj->data3 = "Geek 1/ Set values of copied object Scopy->datal = "Computer "s sci ence"; Scopy->dat Scopy->data3 = "portal": 1/ Print values of Sobj object echo "Sobj->data Sobj->data2Sobj->data3\n"s 1/ Print values of Scopy object ‘echo "Scop >datal Scopy->data2Scopy->data3\n"; Introspection Introspection in PHP of its name, parent class (if any) properties PHP offers a large number of functions ‘The following are the functions to extract the name of their parent class and so on. ffers the useful ability to examine an object's characteristics, such as s, classes, interfaces, and methods. that you can use to accomplish the task basic information about classes such as their name, In-built functions in PHP Introspection = class_exists(): Checks whether a class has been defined. get_class(): Retums the class name of an object feet parent_class(): Retums the class name of a Return object's parent class. is subelass_off):Checks whether an object has a given parent class. get_declared_classes():Returns a list ofall declared classes: get_class_methods():Retumns the names of the class methods sget_class_vars(): Returns the default properties of a class interface _exists():Checks whether the interface is defined. method_exists(): Checks whether an object defines a method. Serialization in PHP: Serialization is a technique used by programmers to preserve their working data in a format that can later be restored to its previous form. PHP@Ini P@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 56 Serializing an object means converting it to a byte stream representation that ean be stored in a file Serialization in PHP is: mostly automati the serialize() and unserialize() functions. it requires little extra work from you, beyond The serialize() converts a storable representation of a value. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string lize data means a sequence of bits so that it in Tink. It is useful for storing or p an be stored in a file. a memory bulfer, or 1 PHP values A seri transmitted across a network connect hout losing their type and structure. around wi Syntax serialize(value) unserialize(): unserialize() can use string to recreate the original variable values from serialized data. Syntax: unserialize(string); <2php Sa=array(‘Shivam' Rahul’, Vilas’); Ss=serialize($a); print_r(Ss); Ss1=unserialize($s); echo "
"; print_r(Ss1); e. converts actual data >

You might also like