PHP – Associative Array ”; Previous Next If each element in a PHP array is a key-value pair, such an array is called an associative array. In this type of array, each value is identified by its associated key and not an index. Associative arrays are used to implement data structures such as dictionary, maps, trees, etc. In PHP, the “=>” symbol is used to establish association between a key and its value. How to Declare an Associative Array in PHP? Both the approaches of declaring an array – the array() function and the square bracket notation – can be used. $arr1 = array( “Maharashtra”=>”Mumbai”, “Telangana”=>”Hyderabad”, “UP”=>”Lucknow”, “Tamilnadu”=>”Chennai” ); $arr2 = [“Maharashtra”=>”Mumbai”, “Telangana”=>”Hyderabad”, “UP”=>”Lucknow”, “Tamilnadu”=>”Chennai”]; If we call the var_dump() function, both the above arrays will show the similar structure − array(4) { [“Maharashtra”]=> string(6) “Mumbai” [“Telangana”]=> string(9) “Hyderabad [“UP”]=> string(7) “Lucknow” [“Tamilnadu”]=> string(7) “Chennai” } The key part of each element in an associative array can be any number (integer, float or Boolean), or a string. The value part can be of any type. However, the float key is cast to an integer. So, a Boolean true/false is used as “1” or “0” as the key. Example Take a look at the following example − <?php $arr1 = array( 10=>”hello”, 5.75=>”world”, -5=>”foo”, false=>”bar” ); var_dump($arr1); ?> It will produce the following output − array(4) { [10]=> string(5) “hello” [5]=> string(5) “world” [-5]=> string(3) “foo” [0]=> string(3) “bar” } Note that the key 5.75 gets rounded to 5, and the key “true” is reflected as “0”. If the same key appears more than once in an array, the key-value pair that appears last will be retained, discarding the association of the key with earlier value. PHP internally treats even an indexed array as an associative array, where the index is actually the key of the value. It means the value at the 0th index has a key equal to “0”, and so on. A var_dump() on an indexed array also brings out this characteristics of a PHP array. Iterating a PHP Associative Array A foreach loop is the easiest and ideal for iterating through an associative array, although any other type of loop can also be used with some maneuver. Example Let us look at the foreach loop implementation, with each key value pair unpacked in two variables. <?php $capitals = array( “Maharashtra”=>”Mumbai”, “Telangana”=>”Hyderabad”, “UP”=>”Lucknow”, “Tamilnadu”=>”Chennai” ); foreach ($capitals as $k=>$v) { echo “Capital of $k is $v n”; } ?> It will produce the following output − Capital of Maharashtra is Mumbai Capital of Telangana is Hyderabad Capital of UP is Lucknow Capital of Tamilnadu is Chennai There is another way of using the foreach loop in PHP, where each element is stored in a variable. We can then separate the key and value parts using array_search() and use them in the loop body. <?php $capitals = array( “Maharashtra”=>”Mumbai”, “Telangana”=>”Hyderabad”, “UP”=>”Lucknow”, “Tamilnadu”=>”Chennai” ); foreach ($capitals as $pair) { $cap = array_search($pair, $capitals); echo “Capital of $cap is $capitals[$cap] n”; } ?> It will produce the following output − Capital of Maharashtra is Mumbai Capital of Telangana is Hyderabad Capital of UP is Lucknow Capital of Tamilnadu is Chennai To use for, while or do-while loop, we have to first get the array of all the keys (use array_keys()), find the size and use it as the test condition in the loop syntax. Example Here is how we can use a for loop to traverse an associative array − <?php $capitals = array( “Maharashtra”=>”Mumbai”, “Telangana”=>”Hyderabad”, “UP”=>”Lucknow”, “Tamilnadu”=>”Chennai” ); $keys=array_keys($capitals); for ($i=0; $i<count($keys); $i++){ $cap = $keys[$i]; echo “Capital of $cap is $capitals[$cap] n”; } ?> It will produce the following output − Capital of Maharashtra is Mumbai Capital of Telangana is Hyderabad Capital of UP is Lucknow Capital of Tamilnadu is Chennai Accessing the Value with its Key In an associative array, the key is the identifier of value instead of index. Hence, to fetch value associated with a certain key, use $arr[key] syntax. The same can be used to update the value of a certain key. Example In the following code, an associative array $arr1 is declared. Another array $arr2 is created such that it stores each pair from $arr1 with the value of each key being doubled. <?php $arr1 = array(“a”=>10, “b”=>20, “c”=>30, “d”=>40); foreach ($arr1 as $k=>$v){ $arr2[$k] = $v*2; } print_r($arr2); ?> It will produce the following output − Array ( [a] => 20 [b] => 40 [c] => 60 [d] => 80 ) The print_r() function used here displays the data stored in the array in an easy to understand human readable form. Print Page Previous Next Advertisements ”;
Category: php
PHP – If…Else Statement
PHP – Ifâ¦Else Statement ”; Previous Next The ability to implement conditional logic is the fundamental requirement of any programming language (PHP included). PHP has three keywords (also called as language constructs) â if, elseif and else â are used to take decision based on the different conditions. The if keyword is the basic construct for the conditional execution of code fragments. More often than not, the if keyword is used in conjunction with else keyword, although it is not always mandatory. If you want to execute some code if a condition is true and another code if the sme condition is false, then use the “if….else” statement. Syntax The usage and syntax of the if statement in PHP is similar to that of the C language. Here is the syntax of if statement in PHP − if (expression) code to be executed if expression is true; else code to be executed if expression is false; The if statement is always followed by a Boolean expression. PHP will execute the statement following the Boolean expression if it evaluates to true. If the Boolean expression evaluates to false, the statement is ignored. If the algorithm needs to execute another statement when the expression is false, it is written after the else keyword. Example Here is a simple PHP code that demonstrates the usage of if else statements. There are two variables $a and $b. The code identifies which one of them is bigger. <?php $a=10; $b=20; if ($a > $b) echo “a is bigger than b”; else echo “a is not bigger than b”; ?> When the above code is run, it displays the following output − a is not bigger than b Interchange the values of “a” and “b” and run again. Now, you will get the following output − a is bigger than b Example The following example will output “Have a nice weekend!” if the current day is Friday, else it will output “Have a nice day!” − <?php $d = date(“D”); if ($d == “Fri”) echo “Have a nice weekend!”; else echo “Have a nice day!”; ?> It will produce the following output − Have a nice weekend! Using endif in PHP PHP code is usually intermixed with HTML script. We can insert HTML code in the if part as well as the else part in PHP code. PHP offers an alternative syntax for if and else statements. Change the opening brace to a colon (:) and the closing brace to endif; so that a HTML block can be added to the if and else part. <?php $d = date(“D”); if ($d == “Fri”): ?> <h2>Have a nice weekend!</h2> <?php else: ?> <h2>Have a nice day!</h2> <?php endif ?> Make sure that the above script is in the document root of PHP server. Visit the URL http://localhost/hello.php. Following output should be displayed in the browser, if the current day is not a Friday − Have a nice day! Using elseif in PHP If you want to execute some code if one of the several conditions are true, then use the elseif statement. The elseif language construct in PHP is a combination of if and else. Similar to else, it specifies an alternative statement to be executed in case the original if expression evaluates to false. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to true. if (expr1) code to be executed if expr1 is true; elseif (expr2) code to be executed if expr2 is true; else code to be executed if expr2 is false; Example Let us modify the above code to display a different message on Sunday, Friday and other days. <?php $d = date(“D”); if ($d == “Fri”) echo “<h3>Have a nice weekend!</h3>”; elseif ($d == “Sun”) echo “<h3>Have a nice Sunday!</h3>”; else echo “<h3>Have a nice day!</h3>”; ?> On a Sunday, the browser shall display the following output − Have a nice Sunday! Example Here is another example to show the use of ifâelselifâelse statements − <?php $x=13; if ($x%2==0) { if ($x%3==0) echo “<h3>$x is divisible by 2 and 3</h3>”; else echo “<h3>$x is divisible by 2 but not divisible by 3</h3>”; } elseif ($x%3==0) echo “<h3>$x is divisible by 3 but not divisible by 2</h3>”; else echo “<h3>$x is not divisible by 3 and not divisible by 2</h3>”; ?> The above code also uses nestedif statements. For the values of x as 13, 12 and 10, the output will be as follows − 13 is not divisible by 3 and not divisible by 2 12 is divisible by 2 and 3 10 is divisible by 2 but not divisible by 3 Print Page Previous Next Advertisements ”;
PHP – var_dump
PHP var_dump() Function ”; Previous Next One of the built-in functions in PHP is the var_dump() function. This function displays structured information such as type and the value of one or more expressions given as arguments to this function. var_dump(mixed $value, mixed …$values): void This function returns all the public, private and protected properties of the objects in the output. The dump information about arrays and objects is properly indented to show the recursive structure. For the built-in integer, float and Boolean varibles, the var_dump() function shows the type and value of the argument variable. Example 1 For example, here is an integer variable − <?php $x = 10; var_dump ($x); ?> The dump information is as follows − int(10) Example 2 Let”s see how it behaves for a float variable − <?php $x = 10.25; var_dump ($x); ?> The var_dump() function returns the following output − float(10.25) Example 3 If the expression is a Boolean value − <?php $x = true; var_dump ($x); ?> It will produce the following output − bool(true) Example 4 For a string variable, the var_dump() function returns the length of the string also. <?php $x = “Hello World”; var_dump ($x); ?> It will produce the following output − string(11) “Hello World” Here we can use the <pre> HTML tag that dislays preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both the spaces and the line breaks. <?php echo “<pre>”; $x = “Hello World”; var_dump ($x); echo “</pre>” ?> It will produce the following output − string(11) “Hello World” Example 5 – Studying the Array Structure Using var_dump() The var_dump() function is useful to study the array structure. In the following example, we have an array with one of the elements of the array being another array. In other words, we have a nested array situation. <?php $x = array(“Hello”, false, 99.99, array(10, 20,30)); var_dump ($x); ?> It will produce the following output − array(4) { [0]=> string(5) “Hello” [1]=> bool(false) [2]=> float(99.99) [3]=> array(3) { [0]=> int(10) [1]=> int(20) [2]=> int(30) } } Example 6 Since “$x” is an indexed array in the previous example, the index starting with “0” along with its value is dumped. In case the array is an associate array, the key-value pair information is dumped. <?php $x = array( “Hello”, false, 99.99, array(1=>10, 2=>20,3=>30) ); var_dump($x); ?> Here, you will get the following output − array(4) { [0]=> string(5) “Hello” [1]=> bool(false) [2]=> float(99.99) [3]=> array(3) { [1]=> int(10) [2]=> int(20) [3]=> int(30) } } When you use var_dump() to show array value, there is no need of using the end tag ” </pre> “. Example 7 The var_dump() function can als reveal the properties of an object representing a class. In the following example, we have declared a Point class with two private properties “x” and “y”. The class constructor initializes the object “p” with the parameters passed to it. The var_dump() function provides the information about the object properties and their corrcponding values. <?php class Point { private int $x; private int $y; public function __construct(int $x, int $y = 0) { $this->x = $x; $this->y = $y; } } $p = new Point(4, 5); var_dump($p) ?> It will produce the following output − object(Point)#1 (2) { [“x”:”Point”:private]=> int(4) [“y”:”Point”:private]=> int(5) } There is a similar built-in function for producing dump in PHP, named as get_defined_vars(). var_dump(get_defined_vars()); It will dump all the defined variables to the browser. Print Page Previous Next Advertisements ”;
PHP – Operators
PHP – Operators Types ”; Previous Next What are Operators in PHP? As in any programming language, PHP also has operators which are symbols (sometimes keywords) that are predefined to perform certain commonly required operations on one or more operands. For example, using the expression “4 + 5” is equal to 9. Here “4” and “5” are called operands and “+” is called an operator. We have the following types of operators in PHP − Arithmetic Operators Comparison Operators Logical Operators Assignment Operators String Operators Array Operators Conditional (or Ternary Operators) This chapter will provide an overview of how you can use these operators in PHP. In the subsequent chapters, we will take a closer look at each of the operators and how they work. Arithmetic Operators in PHP We use Arithmetic operators to perform mathematical operations like addition, subtraction, multiplication, division, etc. on the given operands. Arithmetic operators (excluding the increment and decrement operators) always work on two operands, however the type of these operands should be the same. The following table highligts the arithmetic operators that are supported by PHP. Assume variable “$a” holds 42 and variable “$b” holds 20 − Operator Description Example + Adds two operands $a + $b = 62 – Subtracts second operand from the first $a – $b = 22 * Multiply both operands $a * $b = 840 / Divide numerator by de-numerator $a / $b = 2.1 % Modulus Operator and remainder of after an integer division $a % $b = 2 ++ Increment operator, increases integer value by one $a ++ = 43 — Decrement operator, decreases integer value by one $a — = 42 Comparison Operators in PHP You would use Comparison operators to compare two operands and find the relationship between them. They return a Boolean value (either true or false) based on the outcome of the comparison. The following table highligts the comparison operators that are supported by PHP. Assume variable $a holds 10 and variable $b holds 20, then − Operator Description Example == Checks if the value of two operands are equal or not, if yes then condition becomes true. ($a == $b) is not true != Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. ($a != $b) is true > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. ($a > $b) is false < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. ($a < $b) is true >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. ($a >= $b) is false <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. ($a <= $b) is true Logical Operators in PHP You can use Logical operators in PHP to perform logical operations on multiple expressions together. Logical operators always return Boolean values, either true or false. Logical operators are commonly used with conditional statements and loops to return decisions according to the Boolean conditions. You can also combine them to manipulate Boolean values while dealing with complex expressions. The following table highligts the logical operators that are supported by PHP. Assume variable $a holds 10 and variable $b holds 20, then − Operator Description Example and Called Logical AND operator. If both the operands are true then condition becomes true. (A and B) is true or Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A or B) is true && Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is true || Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A || B) is true ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false Assignment Operators in PHP You can use Assignment operators in PHP to assign or update the values of a given variable with a new value. The right-hand side of the assignment operator holds the value and the left-hand side of the assignment operator is the variable to which the value will be assigned. The data type of both the sides should be the same, else you will get an error. The associativity of assignment operators is from right to left. PHP supports two types of assignment operators − Simple Assignment Operator − It is the most commonly used operator. It is used to assign value to a variable or constant. Compound Assignment Operators − A combination of the assignment operator (=) with other operators like +, *, /, etc. The following table highligts the assignment operators that
PHP – $ and $$ Variables
PHP – $ and $$ Variables ”; Previous Next We know that PHP uses the convention of prefixing the variable names by the “$” symbol. PHP also has the provision of declaring dynamic variables by prefixing two dollar symbols ($$) to the name. A variable variable (or a dynamic variable) can be set and used dynamically. The declaration of a normal variable is like this − $a = ”good”; A dynamic variable takes the value of a normal variable and treats that as the name of the variable. In the above example, “good” can be used as the name of a variable by using two dollar signs “$$” − $$a = ”morning”; We now have two variables: “$a” with contents “good” and “$$a” with contents “morning”. As a result, the following echo statements will produce the same output − echo “$a {$$a}”; echo “$a $good”; Both produce the same output − good morning Example 1 Take a look at this following example − <?php $a = ”good”; $$a = ”morning”; echo “$a {$$a}n”; echo “$a $good”; ?> It will produce the following output − good morning good morning Example 2 Let”s take a look at another example − <?php $x = “foo”; $$x = “bar”; echo “Value of x = ” .$x . “n”; echo ”Value of $$x = ” . $$x . “n”; echo ”Value of foo = ” . $foo; ?> Here, you will get the following output − Value of x = foo Value of $$x = bar Value of foo = bar Using Multiple “$” Symbols Note that the use of “$” symbol is not restricted to two. Any number of dollar symbols can be prefixed. Suppose there is a variable “$x” with “a” as its value. Next, we define $$x=”as”, then “$$x” as well as “$a” will have the same value. Similarly, the statement $$$x=”and” effectively declares a “$as” variable whose value is ”and”. Example Here is a complete example that shows the use of multiple “$” symbols. <?php $php = “a”; $lang = “php”; $World = “lang”; $Hello = “World”; $a = “Hello”; echo ”$a= ” . $a; echo “n”; echo ”$$a= ” . $$a; echo “n”; echo ”$$$a= ” . $$$a; echo “n”; echo ”$$$$a= ” . $$$$a; echo “n”; echo ”$$$$$a= ” . $$$$$a; ?> When you run this code, it will produce the following output − $a= Hello $$a= World $$$a= lang $$$$a= php $$$$$a= a Using Dynamic Variables with Arrays Using dynamic variables with arrays may lead to certain ambiguous situations. With an array “a”, if you write $$a[1], then the parser needs to know if you are refering to “$a[1]” as a variable or if you want “$$a” as the variable and then the [1] index from that variable. To resolve this ambiguity, use ${$a[1]} for the first case and ${$a}[1] for the second. Example Take a look at the following example − <?php $vars = array(“hw”, “os”, “lang”); $var_hw=”Intel”; $var_lang=”PHP”; $var_os=”Linux”; foreach ($vars as $var) echo ${“var_$var”} . “n”; print “$var_hwn$var_osn$var_lang”; ?> It will produce the following output − Intel Linux PHP Intel Linux PHP It may be noted that this technique cannot be used with PHP”s Superglobal arrays (Several predefined variables in PHP are “superglobals”, which means they are available in all scopes throughout a script) within functions or class methods. The variable “$this” is a special variable in PHP and it cannot be referenced dynamically. Print Page Previous Next Advertisements ”;
PHP – Home
PHP Tutorial Table of content PHP Tutorial Why Learn PHP? Advantages of Using PHP Hello World Using PHP PHP Audience PHP Prerequisites Frequently Asked Questions about PHP PDF Version Quick Guide Resources Job Search Discussion What is PHP? PHP is an open-source general purpose scripting language, widely used for website development. It is developed by Rasmus Lerdorf. PHP stands for a recursive acronym PHP: Hypertext Preprocessor. PHP is the world’s most popular server-side programming language. Its latest version PHP 8.2.8, released on July 4th, 2023. PHP is a server-side scripting language that is embedded in HTML. PHP is a cross-platform language, capable of running on all major operating system platforms and with most of the web server programs such as Apache, IIS, lighttpd and nginx. A large number of reusable classes and libraries are available on PEAR and Composer. PEAR (PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or classes. Composer is a dependency management tool in PHP. Why Learn PHP? PHP one of the most preferred languages for creating interactive websites and web applications. PHP scripts can be easily embedded into HTML. With PHP, you can build Web Pages and Web-Based Applications Content Management Systems, and Ecommerce Applications etc. A number of PHP based web frameworks have been developed to speed-up the web application development. The examples are WordPress, Laravel, Symfony etc. Advantages of Using PHP PHP is a MUST for students and working professionals to become great Software Engineers, especially when they are working in Web Development Domain. Some of the most notable advantages of using PHP are listed below − PHP is a multi-paradigm language that supports imperative, functional, object-oriented, and procedural programming methodologies. PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. PHP is integrated with a number of popular databases including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time. PHP supports a number of protocols such as POP3, IMAP, and LDAP. PHP supports distributed object architectures (COM and CORBA), which makes n-tier development possible. PHP is forgiving: PHP language tries to be as forgiving as possible. PHP has a familiar C-like syntax. There are five important characteristics of PHP that make its practical nature possible: Simplicity, Efficiency, Security, Flexibility, and Familiarity. Hello World Using PHP Just to give you a little excitement about PHP, I”m going to give you a small conventional PHP Hello World program. You can try it using the Demo link. <?php echo “Hello, World!”; ?> Audience This PHP tutorial is designed for programmers who are completely unaware of PHP concepts but have a basic understanding on computer programming. Prerequisites Before proceeding with this tutorial, all that you need to have is a basic understanding of computer programming. Knowledge of HTML, CSS, JavaScript, and databases will be an added advantage. Frequently Asked Questions about PHP There are some very Frequently Asked Questions(FAQ) about PHP, this section tries to answer them briefly. Do I Need Prior Programming Experience to Learn PHP? PHP is that”s relatively easy to learn, even for beginners with little or no programming experience. To learn PHP, one needs to only have a basic understanding of computer programming, Internet, database, and HTML. However, prior knowledge of any one programming knowledge is an additional advantage. After learning the core PHP, you can the become proficient in any PHP web framework suitable for the development of applications, such as WordPress, Laravel etc. Is PHP Free to Use? As PHP is open-source, it is free to use. You can also freely distribute the applications built with PHP. The PHP license under which the PHP scripting language is released, implies that, The PHP code can be redistributed in source or binary form. It also means its use and its many libraries and frameworks can be used for both commercial and private use. What are the Applications of PHP? PHP is a server-side scripting language, optimized especially for building dynamic web applications. Developers use PHP to develop applications like content management systems, blogging applications, E-commerce applications, REST APIs etc. A number of PHP frameworks have been developed that are suitable for building applications of a specific type. For example, WordPress is used for building business websites and blogs. Similarly, Laravel is used in E-commerce platforms, Social networking apps, and CRM systems. How Do I Install PHP? To run a PHP application, you need a server, a database server, and a PHP parser software. The most preferred combination is an Apache server, MySQL database, and a PHP module. While one can install all these components individually and configure them, the easiest way is to install pre-compiled binaries bundled together. Examples are XAMPP, WAMP and LAMP. XAMPP is a cross-platform and open-source web server stack package developed by Apache Friends. It consists of the Apache HTTP Server, MariaDB database (an open-source fork of MySQL), and interpreters fo PHP and Perl. The XAMPP software Cn be downloaded from https://www.apachefriends.org/download.html. What Tools and Technologies Work Well with PHP? PHP is a server-side scripting language, that is optimized for building dynamic web applications. One or more blocks of PHP script can be embedded inside HTML code. PHP works seamlessly with HTML and JavaScript
PHP – Introduction
PHP – Introduction ”; Previous Next PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially, PHP was supposed to be an abbreviation for “Personal Home Page”, but it now stands for the recursive initialism “PHP: Hypertext Preprocessor”. Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI) programs in C, which he used to maintain in his personal homepage. Later on, He extended them to work with web forms and to communicate with databases. This implementation of PHP was “Personal Home Page/Forms Interpreter” or PHP/FI. Today, PHP is the world’s most popular server-side programming language for building web applications. Over the years, it has gone through successive revisions and versions. PHP Versions PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He called this suite of scripts “Personal Home Page Tools”. It can be regarded as PHP version 1.0. In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support. PHP/FI was given the version 2.0 status. PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi Gutmans rewrote the PHP parser and acquired the present-day acronym. It provided a mature interface for multiple databases, protocols and APIs, object-oriented programming support, and consistent language syntax. PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many web servers, HTTP sessions, output buffering, secure ways of handling user input and several new language constructs. PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. PHP”s development team includes dozens of developers and others working on PHP-related and supporting projects such as PEAR, PECL, and documentation. PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation (phpng). Developers reworked Zend Engine is called Zend Engine 3. Some of the important features of PHP 7 include its improved performance, reduced memory usage, Return and Scalar Type Declarations and Anonymous Classes. PHP 8.0 was released on 26 November 2020. This is a major version having many significant improvements from its previous versions. One standout feature is Just-in-time compilation (JIT) that can provide substantial performance improvements. The latest version of PHP is 8.2.8, released on July 4th, 2023. PHP Application Areas PHP is one of the most widely used language over the web. Here are some of the application areas of PHP − PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. Although it is especially suited to web development, you can also build desktop standalone applications as PHP also has a command-line interface. You can use PHP-GTK extension to build GUI applications in PHP. PHP is widely used for building web applications, but you are not limited to output only HTML. PHP”s ouput abilities include rich file types, such as images or PDF files, encrypting data, and sending emails. You can also output easily any text, such as JSON or XML. PHP is a cross-platform language, capable of running on all major operating system platforms and with most of the web server programs such as Apache, IIS, lighttpd and nginx. PHP also supports other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM, etc. Here are some more important features of PHP − PHP performs system functions. It can create, open, read, write, and close the files. PHP can handle forms. It can gather data from files, save data to a file, through email you can send data, return data to the user. You add, delete, modify elements within your database through PHP. Access cookies variables and set cookies. Using PHP, you can restrict users to access some pages of your website. It can encrypt data. PHP provides a large number of reusable classes and libraries are available on “PEAR” and “Composer”. PEAR (PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or classes. “Composer” is a dependency management tool in PHP. Print Page Previous Next Advertisements ”;
PHP – Namespaces
PHP – Namespaces ”; Previous Next We often organize the files in different folders. Usually a folder contains files related to a certain objective, or application or category. A folder can’t contain two files with the same name, though different folders may have a file of the same name so that the path of each file is different. The idea of namespaces in PHP is somewhat similar. In PHP, namespaces allow classes or functions or constants of same name be used in different contexts without any conflict, thereby encapsulating these items. A PHP namespace is logical grouping of classes/functions etc., depending on their relevance. Just as a file with same name can exist in two different folders, a class of a certain name can be defined in two namespaces. Further, as we specify the complete path of a file to gain access, we need to specify full name of class along with namespace. As your application size becomes bigger, involving many class and function definitions, giving give a unique name to each class/function may become tedious and not exactly elegant. Using namespaces lets you organize such code blocks in a neat manner. For example, if we need to declare a calculate() function to calculate area as well as tax, instead of defining them as something like calculate_area() and calculate_tax(), we can create two namespaces area and tax and use calculate() inside them. Advantages of Namespace Here are some of the advantages of using namespaces in PHP − Namsepaces help in avoiding name collisions between classes/functions/constants defined by someone with third-party classes/functions/constants. Namespaces provide the ability to alias (or shorten) Extra_Long_Names, thereby improving the readability of source code. PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Namespace names are case – insensitive. Defining a Namespace PHP”s namespace keyword is used to define a new namespace. namespace myspace; A “.php” file containing a namespace must declare the namespace at the top of the file before any other (except the declare directive). Declaration of class, function and constants inside a namespace affects its access. A PHP script may contain other code apart from the definition of a namespace. To load the namespace defined in the same code, PHP has the “use” keyword. use myspace; Example In the following “hello.php” script, we define a hello() function inside myspace namespace, and call it after loading the namespace in the current script. <?php namespace myspace; function hello() { echo “Hello World”; } use myspace; myspacehello(); ?> It will produce the following output − Hello World Note that you must qualify the hello() function with its full name that includes the namespace – myspacehello(). Include Namespace You may have one script consisting of a declaration of a namespace, and the other script in which the namespace is loaded with include statement. a.php <?php namespace myspace { function hello() { echo “Hello World in myspace”; } } ?> b.php <?php include ”a.php”; myspacehello(); ?> It will produce the following output − Hello World in myspace There may be a case where the current script (“b.php” as above) also has a function of the same name as in the included file. The fully qualified function that prepends the namespace, helps the parser to resolve the name conflict. Example Take a look at the following example − <?php include ”a.php”; function hello() { echo “Hello World from current namespace”; } hello(); myspacehello(); ?> It will produce the following output − Hello World from current namespace Hello World in myspace Example As mentioned above, the namespace declaration must be at the top, immediately after the opening <?php tag. Otherwise the parser throws a fatal error. <?php echo “hello” namespace myspace; function hello() { echo “Hello World”; } use myspace; myspacehello(); ?> It will produce the following output − PHP Parse error: syntax error, unexpected token “namespace”, expecting “,” or “;” in /home/cg/root/67771/main.php on line 4 The above error message makes it clear that only the “declare statement” is allowed to appear before the namespace declaration. <?php declare (strict_types=1); namespace myspace; function hello() { echo “Hello World”; } use myspace; myspacehello(); ?> Relative Namespace The objects such as functions, classes and constants may be accessed in the current namespace by referring the with relative namespace paths. In the following example, “b.php” contains a namespace space1myspace with a hello() function and a TEMP constant. The same objects are also defined in namespace space1, present in “a.php”. Obviously, when “b.php” is included in “a.php”, “myspace” is a subspace of “space1”. Hence, hello() from “myspace” is called by prefixing its relative namespace (also the TEMP constant) b.php <?php namespace space1myspace; const TEMP = 10; function hello() { echo “Hello from current namespace:” . __NAMESPACE__ . ; } ?> a.php <?php namespace space1; include ”b.php”; function hello() { echo “Hello from current namespace:” . __NAMESPACE__ . ; } const TEMP = 100; hello(); // current namespace myspacehello(); // sub namespace echo “TEMP : ” . TEMP . ” in ” . __NAMESPACE__ . ; echo “TEMP : ” . myspaceTEMP . ” \in space1\myspacen”; ?> It will produce the following output − Hello from current namespace:space1 Hello from current namespace:space1myspace TEMP : 100 in space1 TEMP : 10 in space1myspace Absolute Namespace You can also access the functions/constants from any namespace by prefixing the absolute namespace path. For example, hello() in “b.php” is “spacemyspacehello()”. a.php <?php namespace space1; include ”b.php”; function hello() { echo “Hello from current namespace:” . __NAMESPACE__ . ; } const TEMP = 100;
PHP – $_SESSION
PHP – $_SESSION ”; Previous Next One of the superglobal variables in PHP, $_SESSION is an associative array of session variables available in the current script. $HTTP_SESSION_VARS also contains the same information, but it is not a superglobal, and it has now been deprecated. What is a Session? A Session is an alternative way to make data accessible across the pages of an entire website. It is the time duration between the time a user establishes a connection with a server and the time the connection is terminated. During this interval, the user may navigate to different pages. Many times, it is desired that some data is persistently available across the pages. This is facilitated by session variables. A session creates a file in a temporary directory on the server where the registered session variables and their values are stored. This data will be available to all the pages on the site during that visit. The server assigns a unique SESSIONID to each session. Since HTTP is a stateless protocol, data in session variables is automatically deleted when the session is terminated. The session_start() Function In order to enable access to session data, the session_start() function must be invoked. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. session_start(array $options = []): bool This function returns true if a session was successfully started, else it returns false. Handling Session Variables To create a new session variable, add a key-value pair in the $_SESSION array − $_SESSION[ “var”]=value; To read back the value of a session variable, you can use echo/print statements, or var_dump() or print_r() functions. echo $_SESSION[ “var”]; To obtain the list of all the session variables in the current session, you can use a foreach loop to traverse the $_SESSION − foreach ($_SESSION as $key=>$val) echo $key . “=>” . $val; To manually clear all the session data, there is session_destroy() function. A specific session variable may also be released by calling the unset() function. unset($_SESSION[ “var”]); List of Session Functions In PHP, there are many built-in functions for managing the session data. Session Functions Description session_abort Discard session array changes and finish session session_cache_expire Return current cache expire session_cache_limiter Get and/or set the current cache limiter session_commit Alias of session_write_close session_create_id Create new session id session_decode Decodes session data from a session encoded string session_destroy Destroys all data registered to a session session_encode Encodes the current session data as a session encoded string session_gc Perform session data garbage collection session_get_cookie_params Get the session cookie parameters session_id Get and/or set the current session id session_is_registered Find out whether a global variable is registered in a session session_module_name Get and/or set the current session module session_name Get and/or set the current session name session_regenerate_id Update the current session id with a newly generated one session_register_shutdown Session shutdown function session_register Register one or more global variables with the current session session_reset Re-initialize session array with original values session_save_path Get and/or set the current session save path session_set_cookie_params Set the session cookie parameters session_set_save_handler Sets user-level session storage functions session_start Start new or resume existing session session_status Returns the current session status session_unregister Unregister a global variable from the current session session_unset Free all session variables session_write_close Write session data and end session Example The following PHP script renders an HTML form. The form data is used to create three session variables. A hyperlink takes the browser to another page, which reads back the session variables. Save this code as “test.php” in the document root folder, and open it in a client browser. Enter the data and press the Submit button. <html> <body> <form action=”<?php echo $_SERVER[”PHP_SELF”];?>” method=”post”> <h3>User”s ID: <input type=”text” name=”ID”/></h3> <h3>Your Name: <input type=”text” name=”name”/></h3> <h3>Enter Age: <input type=”text” name=”age”/></h3> <input type=”submit” value=”Submit”/> </form> <?php session_start(); if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $_SESSION[”UserID”] = $_POST[”ID”]; $_SESSION[”Name”] = $_POST[”name”]; $_SESSION[”age”] = $_POST[”age”]; } echo “Following Session Variables Created: n”; foreach ($_SESSION as $key=>$val) echo “<h3>” . $key . “=>” . $val . “</h3>”; echo “<br/>” . ”<a href=”hello.php”>Click Here</a>”; ?> </body> </html> When you click the “Submit” button, it will show a list of all the session variables created − Next, have the following script in the “hello.php” file and save it. <?php session_start(); echo “<h2>Following Session variables Read:</h2>”; foreach ($_SESSION as $key=>$val) echo “<h3>” . $key . “=>” . $val . “</h3>”; ?> Now, follow the link on the “test.php” page to navigate to “hello.php”. It will show the session variables that are read − Print Page Previous Next Advertisements ”;
PHP – Variable Functions
PHP Variable Handling Functions ”; Previous Next PHP Variable Handling Functions are the inbuilt PHP library functions that enable us to manipulate and test php variables in various ways. Installation There is no installation needed to use PHP variable handling functions; they are part of the PHP core and comes alongwith standard PHP installation. Runtime Configuration This extension has no configuration directives defined in php.ini. PHP Variable Handling Functions Following table lists down all the functions related to PHP Variable Handling. Here column version indicates the earliest version of PHP that supports the function. Sr.No Function & Description Version 1 boolval() Function returns boolean value of a defined variable, i.e, it returns TRUE or FALSE. 5.5.0 2 debug_zval_dump() Function is used to dump a string representation of an internal zend value to output. 4.2.0 3 doubleval() Function is used to return the float value of a defined variable. 4, 5, 7, 8 4 empty() Function is used to check if the defined variable has empty value. 4, 5, 7, 8 5 floatval() Function used return the float value of a defined variable. 4.2.0, 5, 7, 8 6 get_defined_vars() Function is used to return all the defined variables as an array. 4.0.4, 5, 7, 8 7 get_resource_id() Function is used to return an integer identifier for the given resource. 8 8 get_resource_type() Function returns the type a resource of the variable defined. 4.0.2, 5, 7, 8 9 gettype() Function returns the type of the variable defined. 4, 5, 7, 8 10 intval() Function returns integer value of the defined variable. 4, 5, 7, 8 11 is_array() Function is used to check if the defined variable is an array. 4, 5, 7, 8 12 is_bool() Function is used to check if the defined variable is boolean, i.e, it returns true or false value. 4, 5, 7, 8 13 is_callable() Function is used to check if the data in the variable can be called as a function 4.0.6, 5, 7, 8 14 is_countable() Function is used to check if the data in the variable is countable. 7.3.0, 8 15 is_double() Function is used to check if the variable defined is of the type float 4, 5, 7, 8 16 is_float() Function is used to check if the variable defined is an float 4, 5, 7, 8 17 is_int() Function is used to check if the variable defined is of the type integer 4, 5, 7, 8 18 is_integer() Function is used to check if the variable defined is an integer. 4, 5, 7, 8 19 is_iterable() Function is used to check if the data in the variable is an iterable value. 7.1.0, 8 20 is_long() Function is used to check if the variable is of the type integer. 4, 5, 7, 8 21 is_null() Function checks if the variable has NULL value. 4.0.4, 5, 7, 8 22 is_numeric() Function is used to check if the defined variable is numeric or a numeric string. 4, 5, 7, 8 23 is_object() Function is used to check if the variable is an object. 4, 5, 7, 8 24 is_real() Function is used to check if the defined variable is of the type float or not. 4, 5, 7, 8 25 is_resource() Function is used to check if the defined variable is resource. 4, 5, 7, 8 26 is_scalar() Function is used to check if the defined variable is scalar. 4.0.5, 5, 7, 8 27 is_string() Function is used to check if the defined variable is of the type string. 4, 5, 7, 8 28 isset() Function is used to check if a variable is declared and set. 4, 5, 7, 8 29 print_r() Function used to represent or print the data of a variable into a readable format. 4, 5, 7, 8 30 serialize() Function used to convert the data of a variable into a storable representation, so that the data can be stored in a file, a memory buffer 4, 5, 7, 8 31 settype() Function is used to set a variable into a specific type. 4, 5, 7, 8 32 strval() Function is used to return a string value of a variable. 4, 5, 7, 8 33 unserialize() Function is used to unserialize the data of a variable. i.e, this function returns actual data of a serialize variable. 4, 5, 7, 8 34 unset() Function used unset a variable 4, 5, 7, 8 35 var_dump() Function is used to dump information about one or more variables. The information holds type and value of the variable(s). 4, 5, 7, 8 36 var_export() Function returns structured information about a variable.