Category: PHP

  • PHP Tutorial

    What is PHP?

    PHP is an open-source general purpose scripting language, widely used for website development. It is developed by Rasmus Lerdorf in 1994. PHP is a a recursive acronym for ‘PHP: Hypertext Preprocessor’.

    PHP is the world’s most popular server-side programming language. Its latest version PHP 8.4.3, released on January 16th, 2025.

    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
    • E-commerce 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.

    PHP Characteristics

    Below are the main characteristics which make PHP a very good choice for web development −

    1. PHP is Easy to Learn
    2. Open-Source & Free
    3. Cross-Platform Compatibility
    4. Server-Side Scripting
    5. Embedded in HTML
    6. Database Connectivity
    7. Object-Oriented & Procedural Support
    8. Large Standard Library
    9. Supports Various Protocols
    10. Framework Support

    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.

    Here are some of the most popular PHP frameworks −

    • Laravel: Used for building big and secure web applications.
    • CodeIgniter: Very fast and lightweight framework. Good for small projects.
    • Symfony: Used for large and complex applications.
    • CakePHP: Good for making fast and secure websites.
    • FuelPHP: Secure and flexible framework for web development.
    • YII: Best for developing modern Web Applications.
    • Phalcon: It is a PHP full-stack framework.
    • Pixie: Full-stack PHP framework and follows HMVC architecture.
    • Slim: Lightweight micro-framework used for creating RESTful APIs and services.

    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 Edit & Run button.

    <?php
       echo "Hello, World!";
    ?>

    Online PHP Compiler

    Our PHP tutorial provides various examples to explain different concepts. We have provided an online compiler, where you can write, save, run, and share your programs directly from your browser without setting up any development environment. Practice PHP here: Online PHP compiler.

    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.

    Download PHP

    You can download PHP’s latest version from its official websites. Here is the link to open the PHP download page:PHP Downloads & Installation

    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?

    chevron

    Is PHP Free to Use?

    chevron

    What are the Applications of PHP?

    chevron

    How Do I Install PHP?

    chevron

    What Tools and Technologies Work Well with PHP?

    chevron

    Can PHP Be Used for Both Frontend and Backend Development?

    chevron

    Are There Security Concerns with PHP?

    chevron

    What Are the Latest Features and Updates in PHP?

    chevron

    How Long Will it Take to Master PHP?

    chevron

    What Resources Do I Need to Learn PHP?

    chevron

  • Return Type Declarations

    PHP version 7 extends the scalar type declaration feature to the return value of a function also. As per this new provision, the return type declaration specifies the type of value that a function should return. We can declare the following types for return types −

    • int
    • float
    • bool
    • string
    • interfaces
    • array
    • callable

    To implement the return type declaration, a function is defined as −

    functionmyfunction(type$par1,type$param2):type{# function bodyreturn$val;}

    PHP parser is coercive typing by default. You need to declare “strict_types=1” to enforce stricter verification of the type of variable to be returned with the type used in the definition.

    Example

    In the following example, the division() function is defined with a return type as int.

    <?php
       function division(int $x, int $y): int {
    
      $z = $x/$y;
      return $z;
    } $x=20.5; $y=10; echo "First number: " . $x; echo "\nSecond number: " . $y; echo "\nDivision: " . division($x, $y); ?>

    Since the type checking has not been set to strict_types=1, the division take place even if one of the parameters is a non-integer.

    First number: 20.5
    Second number: 10
    Division: 2
    

    However, as soon as you add the declaration of strict_types at the top of the script, the program raises a fatal error message.

    Fatal error: Uncaught TypeError:division():Argument#1 ($x) must be of type int, float given, called in div.php on line 12 and defined in div.php:3
    Stack trace:#0 div.php(12): division(20.5, 10)#1 {main}
       thrown in div.php on line 3

    VS Code warns about the error even before running the code by displaying error lines at the position of error −

    PHP Return Type Declarations

    Example

    To make the division() function return a float instead of int, cast the numerator to float, and see how PHP raises the fatal error −

    <?php
       // declare(strict_types=1);
       function division(int $x, int $y): int {
    
      $z = (float)$x/$y;
      return $z;
    } $x=20; $y=10; echo "First number: " . $x; echo "\nSecond number: " . $y; echo "\nDivision: " . division($x, $y); ?>

    Uncomment the declare statement at the top and run this code here to check its output. It will show an error −

    First number: 20
    Second number: 10PHP Fatal error:  Uncaught TypeError: division(): Return value must be of type int, float returned in /home/cg/root/14246/main.php:5
    Stack trace:
    #0 /home/cg/root/14246/main.php(13): division()
    #1 {main}
      thrown in /home/cg/root/14246/main.php on line 5
    
  • Scalar Type Declarations

    The feature of providing type hints has been in PHP since version 5. Type hinting refers to the practice of providing the data type of a parameter in the function definition. Before PHP 7, it was possible to use only the array, callable, and class for type hints in a function. PHP 7 onwards, you can also insert type hints for parameters of scalar data type such as int, string, bool, etc.

    PHP is a dynamically (and weakly) typed language. Hence, you don’t need to declare the type of the parameter when a function is defined, something which is necessary in a statically type language like C or Java.

    A typical definition of function in PHP is as follows −

    functionaddition($x,$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}

    Here, we assume that the parameters $x and $y are numeric. However, even if the values passed to the function aren’t numeric, the PHP parser tries to cast the variables into compatible type as far as possible.

    If one of the values passed is a string representation of a number, and the second is a numeric variable, PHP casts the string variable to numeric in order to perform the addition operation.

    Example

    Take a look at this following example −

    <?php
       function addition($x, $y) {
    
      echo "First number: " . $x; 
      echo "\nSecond number: " . $y; 
      echo "\nAddition: " . $x+$y;
    } $x="10"; $y=20; addition($x, $y); ?>

    It will produce the following output −

    First number: 10
    Second number: 20
    Addition: 30
    

    However, if $x in the above example is a string that doesn’t hold a valid numeric representation, an error is encountered.

    <?php
       function addition($x, $y) {
    
      echo "First number: " . $x; 
      echo "\nSecond number: " . $y; 
      echo "\nAddition: " . $x+$y;
    } $x="Hello"; $y=20; addition($x, $y); ?>

    Run this code and see how it shows an error.

    Scalar Type Declarations in PHP 7

    A new feature introduced with PHP version 7 allows defining a function with parameters whose data type can be specified within the parenthesis.

    PHP 7 has introduced the following Scalar type declarations −

    • Int
    • Float
    • Bool
    • String
    • Interfaces
    • Array
    • Callable

    Older versions of PHP allowed only the array, callable and class types to be used as type hints. Furthermore, in the older versions of PHP (PHP 5), the fatal error used to be a recoverable error while the new release (PHP 7) returns a throwable error.

    Scalar type declaration is implemented in two modes −

    • Coercive Mode − Coercive is the default mode and need not to be specified.
    • Strict Mode − Strict mode has to be explicitly hinted.

    Coercive Mode

    The addition() function defined in the earlier example can now be re-written by incorporating the type declarations as follows −

    functionaddition(int$x,int$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}

    Note that the parser still casts the incompatible types i.e., string to an int if the string contains an integer as earlier.

    Example

    Take a look at this following example −

    <?php
       function addition(int $x, int $y) {
    
      echo "First number: " . $x;
      echo "\nSecond number: " . $y;
      echo "\nAddition: " . $x+$y;
    } $x="10"; $y=20; echo addition($x, $y); ?>

    It will produce the following output −

    First number: 10
    Second number: 20
    Addition: 30
    

    Obviously, this is because PHP is a weakly typed language, as PHP tries to coerce a variable of string type to an integer. PHP 7 has introduced a strict mode feature that addresses this issue.

    Strict Mode

    To counter the weak type checking of PHP, a strict mode has been introduced. This mode is enabled with a declare statement −

    declare(strict_types=1);

    You should put this statement at the top of the PHP script (usually just below the PHP tag). This means that the strictness of typing for scalars is configured on a per-file basis.

    In the weak mode, the strict_types flag is 0. Setting it to 1 forces the PHP parser to check the compatibility of the parameters and values passed. Add this statement in the above code and check the result. It will show the following error message −

    Fatal error: Uncaught TypeError:addition():Argument#1 ($x) must be of type int, string given, 
    called in add.php on line 12and defined in add.php:4
    
    Stack trace:#0 add.php(12): addition('10', 20)#1 {main}
       thrown in add.php on line 4

    Example

    Here is another example of scalar type declaration in the function definition. The strict mode when enabled raises fatal error if the incompatible types are passed as parameters.

    <?php
    
       // Strict mode
       // declare(strict_types = 1);
       function sum(int ...$ints) {
    
      return array_sum($ints);
    } print(sum(2, '3', 4.1)); ?>

    Uncomment the declare statement at the top of this code and run it. Now it will produce an error −

    Fatal error: Uncaught TypeError: 
    sum(): Argument #2 must be of type int, string given, 
    called in add.php on line 9 and defined in add.php:4
    Stack trace:
    #0 add.php(9): sum(2, '3', 4.1)
    #1 {main}
       thrown in add.php on line 4
    

    The type-hinting feature is mostly used by IDEs to prompt the user about the expected types of the parameters used in the function declaration. The following screenshot shows the VS Code editor popping up the function prototype as you type.

    PHP Scalar Type Declarations
  • Date & Time

    The built-in library of PHP has a wide range of functions that helps in programmatically handling and manipulating date and time information. Date and Time objects in PHP can be created by passing in a string presentation of date/time information, or from the current system’s time.

    PHP provides the DateTime class that defines a number of methods. In this chapter, we will have a detailed view of the various Date and Time related methods available in PHP.

    The date/time features in PHP implements the ISO 8601 calendar, which implements the current leap-day rules from before the Gregorian calendar was in place. The date and time information is internally stored as a 64-bit number.

    Getting the Time Stamp with time()

    PHP’s time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.

    time():int

    The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.

    <?php
       print time();
    ?>

    It will produce the following output −

    1699421347
    

    We can convert a time stamp into a form that humans are comfortable with.

    Converting a Time Stamp with getdate()

    The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().

    The following table lists the elements contained in the array returned by getdate().

    Sr.NoKey & DescriptionExample
    1secondsSeconds past the minutes (0-59)20
    2minutesMinutes past the hour (0 – 59)29
    3hoursHours of the day (0 – 23)22
    4mdayDay of the month (1 – 31)11
    5wdayDay of the week (0 – 6)4
    6monMonth of the year (1 – 12)7
    7yearYear (4 digits)1997
    8ydayDay of year ( 0 – 365 )19
    9weekdayDay of the weekThursday
    10monthMonth of the yearJanuary
    110Timestamp948370048

    Now you have complete control over date and time. You can format this date and time in whatever format you want.

    Example

    Take a look at this following example −

    <?php
       $date_array = getdate();
    
       foreach ( $date_array as $key => $val ){
    
      print "$key = $val\n";
    } $formated_date = "Today's date: "; $formated_date .= $date_array['mday'] . "-"; $formated_date .= $date_array['mon'] . "-"; $formated_date .= $date_array['year']; print $formated_date; ?>

    It will produce the following output −

    seconds = 0
    minutes = 38
    hours = 6
    mday = 8
    wday = 3
    mon = 11
    year = 2023
    yday = 311
    weekday = Wednesday
    month = November
    0 = 1699421880
    Today's date: 8-11-2023
    

    Converting a Time Stamp with date()

    The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.

    date(string$format,?int$timestamp=null):string

    The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.

    The following table lists the codes that a format string can contain −

    Sr.NoFormat & DescriptionExample
    1a‘am’ or ‘pm’ lowercasepm
    2A‘AM’ or ‘PM’ uppercasePM
    3dDay of month, a number with leading zeroes20
    4DDay of week (three letters)Thu
    5FMonth nameJanuary
    6hHour (12-hour format – leading zeroes)12
    7HHour (24-hour format – leading zeroes)22
    8gHour (12-hour format – no leading zeroes)12
    9GHour (24-hour format – no leading zeroes)22
    10iMinutes ( 0 – 59 )23
    11jDay of the month (no leading zeroes20
    12l (Lower ‘L’)Day of the weekThursday
    13LLeap year (‘1’ for yes, ‘0’ for no)1
    14mMonth of year (number – leading zeroes)1
    15MMonth of year (three letters)Jan
    16rThe RFC 2822 formatted dateThu, 21 Dec 2000 16:01:07 +0200
    17nMonth of year (number – no leading zeroes)2
    18sSeconds of hour20
    19UTime stamp948372444
    20yYear (two digits)06
    21YYear (four digits)2006
    22zDay of year (0 – 365)206
    23ZOffset in seconds from GMT+5

    Example

    Take a look at this following example −

    <?php
       print date("m/d/y G.i:s \n", time()) . PHP_EOL;
       print "Today is ";
       print date("j of F Y, \a\\t g.i a", time());
    ?>

    It will produce the following output −

    11/08/23 11.23:08
    
    Today is 8 2023f November 2023, at 11.23 am
    

    Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions.

  • File Include

    The include statement in PHP is similar to the import statement in Java or Python, and #include directive in C/C++. However, there is a slight difference in the way the include statement works in PHP.

    The Java/Python import or #include in C/C++ only loads one or more language constructs such as the functions or classes defined in one file into the current file. In contrast, the include statement in PHP brings in everything in another file into the existing PHP script. It may be a PHP code, a text file, HTML markup, etc.

    The “include” Statement in PHP

    Here is a typical example of how the include statement works in PHP −

    myfile.php

    <?php
       # some PHP code
    ?>

    test.php

    <?php
       include 'myfile.php';
       # PHP script in test.php
    ?>

    The include keyword in PHP is very handy, especially when you need to use the same PHP code (function or class) or HTML markup across multiple PHP scripts in a project. A case in point is the creation of a menu that should appear across all pages of a web application.

    Suppose you want to create a common menu for your website. Then, create a file “menu.php” with the following content.

    <a href="http://www.tutorialspoint.com/index.htm">Home</a> - 
    <a href="http://www.tutorialspoint.com/ebxml">ebXML</a> - 
    <a href="http://www.tutorialspoint.com/ajax">AJAX</a> - 
    <a href="http://www.tutorialspoint.com/perl">PERL</a><br />

    Now create as many pages as you like and include this file to create the header. For example, now your “test.php” file can have the following content −

    <html><body><?php include("menu.php"); ?><p>This is an example to show how to include PHP file!</p></body></html>

    Both the files are assumed to be present in the document root folder of the XAMPP server. Visit http://localhost/test.php URL. It will produce the following output −

    PHP File Include

    When PHP parser encounters the include keyword, it tries to find the specified file in the same directory from which the current script is being executed. If not found, the directories in the “include_path” setting of “php.ini” are searched.

    When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

    Example

    In the following example, we have a “myname.php” script with two variables declared in it. It is included in another script test.php. The variables are loaded in the global scope.

    myname.php

    <?php
       $color = 'green';
       $fruit = 'apple';
    ?>

    test.php

    <?php
       include "myname.php";
       echo "<h2>$fname $lname</h2>";
    ?>

    When the browser visits http://localhost/test.php, it shows −

    Ravi Teja
    

    However, if the file is included inside a function, the variables are a part of the local scope of the function only.

    myname.php

    <?php
       $color = 'green';
       $fruit = 'apple';
    ?>

    test.php

    <?php
       function showname() {
    
      include "myname.php";
    } echo "<h2>$fname $lname</h2>"; ?>

    Now when the browser visits http://localhost/test.php, it shows undefined variable warnings −

    Warning: Undefined variable $fname in C:\xampp\htdocs\test.php on line 7
    Warning: Undefined variable $lname in C:\xampp\htdocs\test.php on line 7
    

    include_once statement

    Just like include, PHP also has the “include_once” keyword. The only difference is that if the code from a file has already been included, it will not be included again, and “include_once” returns true. As the name suggests, the file will be included just once.

    “include_once” may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so it can help avoid problems such as function redefinitions, variable value reassignments, etc.

    PHP – Include vs Require

    The require keyword in PHP is quite similar to the include keyword. The difference between the two is that, upon failure require will produce a fatal E_COMPILE_ERROR level error.

    In other words, require will halt the script, whereas include only emits a warning (E_WARNING) which allows the script to continue.

    require_once keyword

    The “require_once” keyword is similar to require with a subtle difference. If you are using “require_once”, then PHP will check if the file has already been included, and if so, then the same file it will not be included again.

  • Compound Types

    Data types in PHP can be of “scalar type” or “compound type”. Integer, float, Boolean and string types are scalar types, whereas array and object types are classified as compound types. Values of more than one types can be stored together in a single variable of a compound type.

    In PHP, objects and arrays are the two compound data types.

    • An array is an ordered collection of elements of other data types, not necessarily of the same type.
    • An object is an instance of either a built-in or a user defined class, consisting of properties and methods.

    Arrays in PHP

    An array is a data structure that stores one or more data values in a single variable. An array in PHP is an ordered map that associates the values to their keys.

    • There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is to put the array elements inside square brackets.
    • An array which is a collection of only values is called an indexed array. Each value is identified by a positional index staring from 0.
    • If the array is a collection of key-value pairs, it is called as an associative array. The key component of the pair can be a number or a string, whereas the value part can be of any type.

    The array() Function in PHP

    The built-in array() function uses the parameters given to it and returns an object of array type. One or more comma-separated parameters are the elements in the array.

    array(mixed...$values):array

    Each value in the parenthesis may be either a singular value (it may be a number, string, any object or even another array), or a key-value pair. The association between the key and its value is denoted by the “=>” symbol.

    Example

    Take a look at this following example −

    $arr1=array(10,"asd",1.55,true);$arr2=array("one"=>1,"two"=>2,"three"=>3);$arr3=array(array(10,20,30),array("Ten","Twenty","Thirty"),array("physics"=>70,"chemistry"=>80,"maths"=>90));

    Using Square Brackets [ ]

    Instead of the array() function, the comma-separated array elements may also be put inside the square brackets to declare an array object. In this case too, the elements may be singular values or a string or another array.

    $arr1=[10,"asd",1.55,true];$arr2=["one"=>1,"two"=>2,"three"=>3];$arr3=[[10,20,30],["Ten","Twenty","Thirty"],["physics"=>70,"chemistry"=>80,"maths"=>90]];

    Accessing Array Elements

    To access any element from a given array, you can use the array[key] syntax. For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.

    <?php
       $arr1 = [10, 20, 30];
       $arr2 = array("one"=>1, "two"=>2, "three"=>3);
    
       var_dump($arr1[1]);
       var_dump($arr2["two"]);
    ?>

    It will produce the following output −

    int(20)
    int(2)
    

    Array Traversal in PHP

    You can also use the foreach loop to iterate through an indexed array.

    <?php
       $arr1 = [10, 20, 30, 40, 50];
       foreach ($arr1 as $val){
    
      echo "$val\n";
    } ?>

    It will produce the following output −

    10
    20
    30
    40
    50
    

    Note that PHP internally treats the indexed array as an associative array, with the index being treated as the key. This fact can be verified by the var_dump() output of the array.

    We can unpack each element of the indexed array in the key and value variables with the foreach syntax −

    <?php
       $arr1 = [10, 20, 30, 40, 50];
       foreach ($arr1 as $key => $val){
    
      echo "arr1&#91;$key] = $val" . "\n";
    } ?>

    It will produce the following output −

    arr1[0] = 10
    arr1[1] = 20
    arr1[2] = 30
    arr1[3] = 40
    arr1[4] = 50
    

    The foreach loop is also used for iterating through an associative array, although any other type of loop can also be used with some maneuver.

    Let us look at the foreach loop implementation, with each k-v pair unpacked in two variables.

    <?php
       $capitals = array(
    
      "Maharashtra"=&gt;"Mumbai", 
      "Telangana"=&gt;"Hyderabad", 
      "UP"=&gt;"Lucknow", 
      "Tamilnadu"=&gt;"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
    

    Objects in PHP

    In PHP, an object is a compound data type. It is an instance of either a built in or user defined class. Given below is a simple PHP class −

    classSayHello{functionhello(){echo"Hello World";}}

    To declare an object of a class, we need to use the new operator.

    $obj=newSayHello;

    We can now call its method −

    <?php
       class SayHello {
    
      function hello() {
         echo "Hello World". PHP_EOL;
      }
    } $obj=new SayHello; var_dump(gettype($obj)); $obj->hello(); ?>

    It will produce the following output −

    string(6) "object"
    Hello World
    

    stdClass

    PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting. An object of stdClass is null to begin with. We can add properties to it dynamically.

    <?php
       $obj=new stdClass;
       $obj->name="Deepak";
       $obj->age=21;
       $obj->marks=75;
    
       print_r($obj);
    ?>

    It will produce the following output −

    stdClass Object (
       [name] => Deepak
       [age] => 21
       [marks] => 75
    )
    

    Array to Object Conversion in PHP

    An array in PHP can be typecast to an object as follows −

    <?php
       $arr=array("name"=>"Deepak", "age"=>21, "marks"=>75);
       $obj=(object)$arr;
    
       print_r($obj);
    ?>

    It will produce the following output −

    stdClass Object (
       [name] => Deepak
       [age] => 21
       [marks] => 75
    )
    

    Object to Array Conversion in PHP

    Conversely, an object can be cast to an array. Take a look at the following example −

    <?php
       $obj=new stdClass;
       $obj->name="Deepak";
       $obj->age=21;
       $obj->marks=75;
    
       $arr=(array)$obj;
       print_r($arr);
    ?>

    It will produce the following output −

    Array
    (
       [name] => Deepak
       [age] => 21
       [marks] => 75
    )
    

    Scalar Type to Object Type Conversion in PHP

    A variable of any scalar type can also be converted to an object by type casting. The value of the scalar variable becomes the value of the object’s scalar property.

    <?php
       $name="Deepak";
       $age=21;
       $percent=75.50;
    
       $obj1=(object)$name;
       print_r($obj1);
    
       $obj2=(object)$age;
       print_r($obj2);
    
       $obj3=(object)$percent;
       print_r($obj3);
    ?>

    It will produce the following output −

    stdClass Object
    (
       [scalar] => Deepak
    )
    stdClass Object
    (
       [scalar] => 21
    )
    stdClass Object
    (
       [scalar] => 75.5
    )
    
  • Heredoc & Nowdoc

    PHP provides two alternatives for declaring single or double quoted strings in the form of heredoc and newdoc syntax.

    • The single quoted string doesn’t interpret the escape characters and doesn’t expand the variables.
    • On the other hand, if you declare a double quoted string that contains a double quote character itself, you need to escape it by the “\” symbol. The heredoc syntax provides a convenient method.

    Heredoc Strings in PHP

    The heredoc strings in PHP are much like double-quoted strings, without the double-quotes. It means that they don’t need to escape quotes and expand variables.

    Heredoc Syntax

    $str=<<<IDENTIFIER
    place a string here
    it can span multiple lines
    and include single quote ' and double quotes "
    IDENTIFIER;

    First, start with the “<<<” operator. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The string can span multiple lines and includes single quotes (‘) or double quotes (“).

    The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string.

    Example

    The identifier must contain only alphanumeric characters and underscores and start with an underscore or a non-digit character. The closing identifier should not contain any other characters except a semicolon (;). Furthermore, the character before and after the closing identifier must be a newline character only.

    Take a look at the following example −

    <?php  
       $str1 = <<<STRING
       Hello World
    
      PHP Tutorial
         by TutorialsPoint
    STRING; echo $str1; ?>

    It will produce the following output −

    Hello World
    
    PHP Tutorial
        by TutorialsPoint

    Example

    The closing identifier may or may not contain indentation after the first column in the editor. Indentation, if any, will be stripped off. However, the closing identifier must not be indented further than any lines of the body. Otherwise, a ParseError will be raised. Take a look at the following example and its output −

    <?php  
       $str1 = <<<STRING
       Hello World
    
      PHP Tutorial
    by TutorialsPoint
         STRING;
         
    echo $str1; ?>

    It will produce the following output −

    PHP Parse error:  Invalid body indentation level 
    (expecting an indentation level of at least 16) in hello.php on line 3
    

    Example

    The quotes in a heredoc do not need to be escaped, but the PHP escape sequences can still be used. Heredoc syntax also expands the variables.

    <?php  
       $lang="PHP";
       echo <<<EOS
       Heredoc strings in $lang expand vriables.
       The escape sequences are also interpreted.
       Here, the hexdecimal ASCII characters produce \x50\x48\x50
       EOS;
    ?>

    It will produce the following output −

    Heredoc strings in PHP expand vriables.
    The escape sequences are also interpreted.
    Here, the hexdecimal ASCII characters produce PHP
    

    Nowdoc Strings in PHP

    A nowdoc string in PHP is similar to a heredoc string except that it doesn’t expand the variables, neither does it interpret the escape sequences.

    <?php  
       $lang="PHP";
    
       $str = <<<'IDENTIFIER'
       This is an example of Nowdoc string.
       it can span multiple lines
       and include single quote ' and double quotes "
       IT doesn't expand the value of $lang variable
       IDENTIFIER;
    
       echo $str;
    ?>

    It will produce the following output −

    This is an example of Nowdoc string.
    it can span multiple lines
    and include single quote ' and double quotes "
    IT doesn't expand the value of $lang variable
    

    The nowdoc’s syntax is similar to the heredoc’s syntax except that the identifier which follows the “<<<” operator needs to be enclosed in single quotes. The nowdoc’s identifier also follows the rules for the heredoc identifier.

    Heredoc strings are like double-quoted strings without escaping. Nowdoc strings are like single-quoted strings without escaping.

  • Maths Functions

    To enable mathematical operations, PHP has mathematical (arithmetic) operators and a number of mathematical functions. In this chapter, the following mathematical functions are explained with examples.

    PHP abs() Function

    The abs() function is an in-built function in PHP iterpreter. This function accepts any number as argument and returns a positive value, disregarding its sign. Absolute value of any number is always positive.

    abs(mixed$num)

    PHP abs() function returns the absolute value of num. If the data type of num is float, its return type will also be float. For integer parameter, the return type is integer.

    Example

    Take a look at this following example −

    <?php
       $num=-9.99;
       echo "negative float number: " . $num . "\n";
       echo "absolute value : " . abs($num) . "\n"; 
    
       $num=25.55;
       echo "positive float number: " . $num . "\n";
       echo "absolute value : " . abs($num). "\n";
    
       $num=-45;
       echo "negative integer number: " . $num . "\n";
       echo "absolute value : " . abs($num) . "\n"; 
    
       $num=25;
       echo "positive integer number: " . $num . "\n";
       echo "absolute value : " . abs($num);
    ?>

    It will produce the following output −

    negative float number: -9.99
    absolute value : 9.99
    positive float number: 25.55
    absolute value : 25.55
    negative integer number: -45
    absolute value : 45
    positive integer number: 25
    absolute value : 25
    

    PHP ceil() Function

    The ceil() function is an in-built function in PHP iterpreter. This function accepts any float number as argument and rounds it up to the next highest integer. This function always returns a float number as the range of float is bigger than that of integer.

    ceil(float$num):float

    PHP ceil() function returns the smallest integer value that is bigger than or equal to given parameter.

    Example 1

    The following code rounds 5.78 to its next highest integer which is 6

    <?php
       $arg=5.78; 
       $val=ceil($arg);
       echo "ceil(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    ceil(5.78) = 6
    

    Example 2

    The following example shows how you can find the next highest integer of 15.05.

    <?php
       $arg=15.05; 
       $val=ceil($arg);
       echo "ceil(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    ceil(15.05) = 16
    

    Example 3

    For negative number, it is rounded towards 0.

    <?php
       $arg=-3.95; 
       $val=ceil($arg);
       echo "ceil(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    ceil(-3.95) = -3
    

    PHP exp() Function

    The exp() function calculates exponent of e that is Euler Number. PHP has a predefined constant M_E that represents Euler Number and is equal to 2.7182818284590452354. Hence, exp(x) returns 2.7182818284590452354x

    This function always returns a float.

    exp(float$arg):float

    PHP exp() function returns the Euler Number e raised to given arg. Note that e is the base of natural algorithm. The exp() function is the inverse of natural logarithm.

    Example 1

    One of the predefined constants in PHP is M_LN2 which stands for loge2 and is equal to 0.69314718055994530942. So, the exp() of this value will return 2.

    <?php
       echo "exp(" . M_LN2 . ") = " . exp(M_LN2);
    ?>

    It will produce the following output −

    exp(0.69314718055995) = 2
    

    Example 2

    M_LN10 is another predefined constant representing loge10. This program calculates exp(M_LN10) and returns 10.

    <?php
       echo "exp(" . M_LN10 . ") = " . exp(M_LN10);
    ?>

    It will produce the following output −

    exp(2.302585092994) = 10
    

    PHP floor() Function

    The floor() function is another in-built function in PHP interpreter. This function accepts any float number as argument and rounds it down to the next lowest integer. This function always returns a float number as the range of float is bigger than that of integer.

    floor(float$num):float

    PHP floor() function returns the largest integer less than or equal to the given parameter.

    Example 1

    The following example shows how to round 15.05 to its next highest integer which is 15

    <?php
       $arg=15.05; 
       $val=floor($arg);
       echo "floor(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    floor(15.05) = 15
    

    Example 2

    The following example shows how to find the next lowest integer of 5.78.

    <?php
       $arg=5.78; 
       $val=floor($arg);
       echo "floor(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    floor(5.78) = 5
    

    Example 3

    Negative numbers are rounded away from 0.

    <?php
       $arg=-3.95; 
       $val=floor($arg);
       echo "floor(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    floor(-3.95) = -4
    

    PHP intdiv() Function

    The intdiv() function returns the integer quotient of two integer parameters. If x/y results in “i” as division and “r” as remainder, then −

    x = y*i+r
    

    In this case, intdiv(x,y) returns “i”

    intdiv(int$x,int$y):int

    The “x” parameter forms numerator part of the division expression, while the “y” parameter forms the denominator part of the division expression.

    PHP intdiv() function returns the integer quotient of division of “x” by “y”. The return value is positive if both the parameters are positive or both the parameters are negative.

    Example 1

    The following example shows that if the numerator is less than the denominator, then intdiv() function returns 0.

    <?php
       $x=10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
       $r=intdiv($y, $x);
       echo "intdiv(" . $y . "," . $x . ") = " . $r;
    ?>

    It will produce the following output −

    intdiv(10,3) = 3
    intdiv(3,10) = 0
    

    Example 2

    In the following example, intdiv() function returns a negative integer because either the numerator or the denominator is negative.

    <?php
       $x=10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    
       $x=10;
       $y=-3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    
       $x=-10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    
       $x=-10;
       $y=-3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r ;
    ?>

    It will produce the following output −

    intdiv(10,3) = 3
    intdiv(10,-3) = -3
    intdiv(-10,3) = -3
    intdiv(-10,-3) = 3
    

    Example 3

    Denominator is 0 in the following example. It results in DivisionByZeroError exception.

    <?php
       $x=10;
       $y=0; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    ?>

    It will produce the following output −

    PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero
    

    Example 4

    The fractional parts in both the parameters are ignored. PHP intdiv() function is applied only to the integer parts.

    <?php
       $x=2.90;
       $y=1.90; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "";
    ?>

    It will produce the following output −

    intdiv(2.9,1.9) = 2
    

    PHP log10() Function

    The log10 () function calculates the base-10 logarithm of a number. Base-10 logarithm is also called common or standard algorithm. The log10(x) function calculates log10x. It is related to natural algorithm by the following equation −

    log10x=logex/loge10 ; So that
    log10100=loge100/loge10 =2

    In PHP, log10 is represented by log10() function

    log10(float$arg):float

    PHP log10() function returns the base-10 logarithm of arg.

    Example 1

    The following code calculates the base-10 logarithm of 100

    <?php
       $arg=100;
       echo "log10(" . $arg. ")=" . log10($arg) . "";
    ?>

    It will produce the following output −

    log10(100)=2
    

    Example 2

    The following code calculates the base-10 logarithm of Euler Number M_E. The result is equal to a predefined constant M_LOG10E

    <?php
       $arg=M_E;
       echo "log10(" . $arg. ")=" . log10($arg) . "\n";
       echo "predefined constant M_LOG10E=" . M_LOG10E;
    ?>

    It will produce the following output −

    log10(2.718281828459)=0.43429448190325
    predefined constant M_LOG10E=0.43429448190325
    

    Example 3

    The following code calculates log100 and returns -∞.

    <?php
       $arg=0;
       echo "log10(" . $arg. ")=" . log10($arg) . "";
    ?>

    It will produce the following output −

    log10(0)=-INF
    

    Example 4

    Similarly sqrt(-1) results in NAN. Hence, its log10() also returns NAN.

    <?php
       $arg=sqrt(-1);
       echo "log10(" . $arg. ")=" . log10($arg) . "";
    ?>

    It will produce the following output −

    log10(NAN)=NAN
    

    PHP max() Function

    The max () function returns the highest element in an array, or the highest amongst two or more comma separated parameters.

    max(array$values):mixed

    Or,

    max(mixed$value1[,mixed $...]):mixed
    • If only one parameter is given, it should be an array of values which may be of same or different types.
    • If two or more parameters are given, they should be any comparable values of same or different types.

    PHP max() function returns the highest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned.

    Example 1

    The following code returns the highest value from a numeric array.

    <?php
       $arg=array(23, 5.55, 142, 56, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "max = " . max($arg);
    ?>

    It will produce the following output −

    array=23,5.55,142,56,99,
    max = 142
    

    Example 2

    The following code returns max() from an array of strings.

    <?php
       $arg=array("Java", "Angular", "PHP", "C", "Kotlin");
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "max = " . max($arg);
    ?>

    It will produce the following output −

    array=Java,Angular,PHP,C,Kotlin,
    max = PHP
    

    Example 3

    In the following example, a series of string values is provided to the max() function. Let’s see how it behaves −

    <?php
       $val1="Java";
       $val2="Angular";
       $val3="PHP";
       $val4="C";
       $val5="Kotlin";
       echo "values=" . $val1 . "," . $val2 . "," . $val3 . "," . 	$val4 . "," . $val5 . "\n";
       echo "max = " . max($val1, $val2, $val3,$val4,$val5);
    ?>

    It will produce the following output −

    values=Java,Angular,PHP,C,Kotlin
    max = PHP
    

    Example 4

    In this example, the given array is a collection of mixed data types.

    <?php
       $arg=array(23, "Java", 142, 1e2, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "max = " . max($arg);
    ?>

    It will produce the following output −

    array=23,Java,142,100,99,
    max = 142
    

    PHP min() Function

    The min () function returns the lowest element in an array, or the lowest amongst two or more comma separated parameters.

    min(array$values):mixed

    Or,

    min(mixed$value1[,mixed $...]):mixed
    • If only one parameter is given, it should be an array of values which may be of same or different types
    • If two or more parameters are given, they should be any comparable values of same or different types

    PHP min() function returns the lowest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned

    Example 1

    The following code returns the smallest value from numeric array.

    <?php
       $arg=array(23, 5.55, 142, 56, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "min = " . min($arg);
    ?>

    It will produce the following output −

    array=23,5.55,142,56,99,
    min = 5.55
    

    Example 2

    The following code returns min() from an array of strings.

    <?php
       $arg=array("Java", "Angular", "PHP", "C", "Kotlin");
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "min = " . min($arg);
    ?>

    It will produce the following output −

    array=Java,Angular,PHP,C,Kotlin,
    min = Angular
    

    Example 3

    In this example, a series of string values is provided to the min() function.

    <?php
       $val1="Java";
       $val2="Angular";
       $val3="PHP";
       $val4="C";
       $val5="Kotlin";
       echo "values=" . $val1 . "," . $val2 . "," . $val3 . "," . 	$val4 . "," . $val5 . "\n";
       echo "min = " . min($val1, $val2, $val3,$val4,$val5);
    ?>

    It will produce the following output −

    values=Java,Angular,PHP,C,Kotlin
    min = Angular
    

    Example 4

    In this example, the given array is a collection of mixed data types.

    <?php
       $arg=array(23, "Java", 142, 1e2, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "min = " . min($arg);
    ?>

    It will produce the following output −

    array=23,Java,142,100,99,
    min = 23
    

    PHP pow() Function

    The pow () function is used to compute the power of a certain number. It returns xy calculation, also termed as x raised to y. PHP also provides “**” as exponentiation operator.

    So, pow(x,y) returns xy which is same as x**y.

    pow(number$base,number$exp):number

    The first parameter is the base to be raised. The second parameter is the power to which base needs to be raised.

    PHP pow() function returns the base raised to the power of exp. If both arguments are non-negative integers, the result is returned as integer, otherwise it is returned as a float.

    Example 1

    The following example calculates 102 using pow() function −

    <?php
       echo "pow(10,2) = " . pow(10,2);
       echo " using ** operator " . 10**2;
    ?>

    It will produce the following output −

    pow(10,2) = 100 using ** operator 100
    

    Example 2

    Any number raised to 0 results in 1. This is verified in the following example −

    <?php
       $x=10;
       $y=0;
       echo "pow(" . $x, "," . $y . ")=". pow($x,$y);
    ?>

    It will produce the following output −

    pow(10,0)=1
    

    Example 3

    The following example shows how you can compute the square root of 100 using the pow() function −

    <?php
       $x=100;
       $y=0.5;
       echo "pow(" . $x, "," . $y . ")=". pow($x,$y) . "\n";
       echo "using sqrt() function : ". sqrt(100);
    ?>

    It will produce the following output −

    pow(100,0.5)=10
    using sqrt() function : 10
    

    Example 4

    This example shows how you can use the pow() function to calculate the area of a circle.

    <?php
       $radius=5;
       echo "radius = " . $radius . " area = " . M_PI*pow(5,2);
    ?>

    It will produce the following output −

    radius = 5 area = 78.539816339745
    

    PHP round() Function

    The round() function proves useful in rounding any floating point number upto a desired precision level. Positive precision parameter causes the number to be rounded after the decimal point; whereas with negative precision, rounding occurs before the decimal point. Precision is “0” by default.

    For example, round(10.6) returns 11, round(10.2) returns 10. The function always returns a floating point number.

    This function also has another optional parameter called mode that takes one of the redefined constants described later.

    round(float$value,int$precision,int$mode):float

    Parameters

    • Value − A float number to be rounded.
    • Precision − Number of decimal digits to round to. Default is 0. Positive precision rounds given number after decimal point. Negative precision rounds the given number before decimal point.
    • Mode − One of the following predefined constants.
    Sr.NoConstant & Description
    1PHP_ROUND_HALF_UPRounds number away from 0 when it is half way there. Hence, 1.5 becomes 2 and -1.5 to -2
    2PHP_ROUND_HALF_DOWNRounds number towards 0 when it is half way there. Hence 1.5 becomes 1 and -1.5 to -1
    3PHP_ROUND_HALF_EVENRounds the number to nearest even value
    4PHP_ROUND_HALF_ODDRounds the number to nearest odd value

    PHP round() function returns a float number that by rounding the value to a desired precision.

    Example 1

    The following code rounds the given number to positive precision values −

    <?php
       $arg=1234.567;
       echo "round(" . $arg . ") = " . round($arg) . "\n";
       echo "round(" . $arg . ",1) = " . round($arg,1) . "\n";
       echo "round(" . $arg . ",2) = " . round($arg,2) . "";
    ?>

    It will produce the following output −

    round(1234.567) = 1235
    round(1234.567,1) = 1234.6
    round(1234.567,2) = 1234.57
    

    Example 2

    The following code rounds the number to negative precision values −

    <?php
       $arg=1234.567;
       echo "round(" . $arg . ") = " . round($arg) . "\n";
       echo "round(" . $arg . ",-1) = " . round($arg,-1) . "\n";
       echo "round(" . $arg . ",-2) = " . round($arg,-2) . "";
    ?>

    It will produce the following output −

    round(1234.567) = 1235
    round(1234.567,-1) = 1230
    round(1234.567,-2) = 1200
    

    Example 3

    The following code uses UP and DOWN mode constants for rounding −

    <?php
       echo "round(3.45,HALF_UP) = " . round(3.45,0, PHP_ROUND_HALF_UP) . "\n";
       echo "round(3.75 HALF_UP) = " . round(3.75, 1, PHP_ROUND_HALF_DOWN) . "";
    ?>

    It will produce the following output −

    round(3.45,HALF_UP) = 3
    round(3.75 HALF_UP) = 3.7
    

    Example 4

    The following code uses ODD and EVEN modes for rounding −

    <?php
       echo "round( 3.45,HALF_ODD) = " . round(3.45,0, PHP_ROUND_HALF_ODD) . "\n";
       echo "round(3.78 HALF_EVEN) = " . round(3.78, 0, PHP_ROUND_HALF_EVEN) . "";
    ?>

    It will produce the following output −

    round(3.45,HALF_ODD) = 3
    round(3.78, HALF_EVEN) = 4
    

    PHP sqrt() Function

    The sqrt() function returns the square root of a positive float number. Since square root for a negative number is not defined, it returns NAN. This is one of the most commonly used functions. This function always returns a floating point number.

    sqrt(float$arg):float

    PHP sqrt() function returns the square root of the given arg number. For negative numbers, the function returns NAN.

    Example 1

    The following code calculates the square root of 100 −

    <?php
       $arg = 100;
       echo "Square root of " . $arg . "=" . sqrt($arg) . "";
    ?>

    It will produce the following output −

    Square root of 100=10
    

    Example 2

    For sqrt(2), 1/sqrt(2) and sqrt(3), PHP has special predefined constants M_SQRT2, M_SQRT1_2 and M_SQRT3, respectively.

    <?php
       echo "sqrt(2) = " . sqrt(2) . "\n";
       echo "M_SQRT2 = " . M_SQRT2. "\n";
       echo "sqrt(3) = " . sqrt(3) . "\n";
       echo "M_SQRT3 = " . M_SQRT3 . "\n";
       echo "1/sqrt(2)) = " . 1/sqrt(2) . "\n";
       echo "M_SQRT1_2 = " . M_SQRT1_2 . "";
    ?>

    It will produce the following output −

    sqrt(2) = 1.4142135623731
    M_SQRT2 = 1.4142135623731
    sqrt(3) = 1.7320508075689
    M_SQRT3 = 1.7320508075689
    1/sqrt(2)) = 0.70710678118655
    M_SQRT1_2 = 0.70710678118655
    

    Example 3

    The mathematical constants M_SQRTPI and M_2_SQRTPI represent values of sqrt(Π) and 2/sqrt(Π).

    <?php
       echo "sqrt(pi) = " . sqrt(M_PI) . "\n";
       echo "M_SQRTPI = " . M_SQRTPI. "\n";
       echo "2/sqrt(pi) = " . 2/sqrt(M_PI) . "\n";
       echo "M_2_SQRTPI = " . M_2_SQRTPI . "";
    ?>

    It will produce the following output −

    sqrt(pi) = 1.7724538509055
    M_SQRTPI = 1.7724538509055
    2/sqrt(pi) = 1.1283791670955
    M_2_SQRTPI = 1.1283791670955
    

    Example 4

    sqrt(-1) is undefined, hence it returns NAN.

    <?php
       echo "sqrt(-1) = " . sqrt(-1) . "";
    ?>

    It will produce the following output −

    sqrt(-1) = NAN
    

    Predefined Mathematical Constants

    In addition to the above mathematical functions, PHP also has the following list of predefined mathematical constants −

    ConstantValueDescription
    M_PI3.14159265358979323846Pi
    M_E2.7182818284590452354Euler Number e
    M_LOG2E1.4426950408889634074log2 e
    M_LOG10E0.43429448190325182765log10 e
    M_LN20.69314718055994530942loge 2
    M_LN10M_LN10 2.30258509299404568402 loge 10loge 10
    M_PI_21.57079632679489661923pi/2
    M_PI_40.78539816339744830962pi/4
    M_1_PI0.318309886183790671541/pi
    M_2_PI0.636619772367581343082/pi
    M_SQRTPI1.77245385090551602729sqrt(pi)
    M_2_SQRTPI1.128379167095512573902/sqrt(pi)
    M_SQRT21.41421356237309504880sqrt(2)
    M_SQRT31.73205080756887729352sqrt(3)
    M_SQRT1_20.707106781186547524401/sqrt(2)
    M_LNPI1.14472988584940017414loge(pi)
    M_EULER0.57721566490153286061Euler constant
    PHP_ROUND_HALF_UP1Round halves up
    PHP_ROUND_HALF_DOWN2Round halves down
    PHP_ROUND_HALF_EVEN3Round halves to even numbers
    PHP_ROUND_HALF_ODD4Round halves to odd numbers
    NANNANNot A Number
    INFINFInfinity
  • Files & I/O

    This chapter will explain following functions related to files −

    • Opening a File
    • Reading a File
    • Writing a File
    • Closing a File

    Opening and Closing Files

    The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.

    Files modes can be specified as one of the six options in this table.

    Sr.NoMode & Purpose
    1rOpens the file for reading only.Places the file pointer at the beginning of the file.
    2r+Opens the file for reading and writing.Places the file pointer at the beginning of the file.
    3wOpens the file for writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
    4w+Opens the file for reading and writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
    5aOpens the file for writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.
    6a+Opens the file for reading and writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.

    If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.

    After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

    Reading a File

    Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.

    The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

    So here are the steps required to read a file with PHP.

    • Open a file using fopen() function.
    • Get the file’s length using filesize() function.
    • Read the file’s content using fread() function.
    • Close the file with fclose() function.

    Example

    The following example assigns the content of a text file to a variable then displays those contents on the web page.

    <html><head><title>Reading a file using PHP</title></head><body><?php
    
      $filename = "tmp.txt";
      $file = fopen( $filename, "r" );
      if( $file == false ) {
         echo ( "Error in opening file" );
         exit();
      }
      $filesize = filesize( $filename );
      $filetext = fread( $file, $filesize );
      fclose( $file );
      echo ( "File size : $filesize bytes" );
      echo ( "&lt;pre&gt;$filetext&lt;/pre&gt;" );
    ?></body></html>

    It will produce the following result −

    Reading File

    Writing a File

    A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.

    Example

    The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument

    <?php
       $filename = "/home/user/guest/newfile.txt";
       $file = fopen( $filename, "w" );
       
       if( $file == false ) {
    
      echo ( "Error in opening new file" );
      exit();
    } fwrite( $file, "This is a simple test\n" ); fclose( $file ); ?><html><head><title>Writing a file using PHP</title></head><body><?php
      $filename = "newfile.txt";
      $file = fopen( $filename, "r" );
      if( $file == false ) {
         echo ( "Error in opening file" );
         exit();
      }
      $filesize = filesize( $filename );
      $filetext = fread( $file, $filesize );
      fclose( $file );
      echo ( "File size : $filesize bytes" );
      echo ( "$filetext" );
      echo("file name: $filename");
    ?></body></html>

    It will produce the following result −

    Writing File

    We have covered all the function related to file input and out in PHP File System Function chapter.

  • Integers

    Integer is one of the built-in scalar types in PHP. A whole number, without a decimal point in the literal, is of the type “int” in PHP. An integer can be represented in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation.

    To use octal notation, a number is preceded with “0o” or “0O” (PHP 8.1.0 and earlier). From PHP 8.1.0 onwards, a number prefixed with “0” and without a decimal point is an octal number.

    To use hexadecimal notation, precede the number with “0x”. To use binary notation, precede the number with “0b”.

    Example

    Take a look at this following example −

    <?php
       $a = 1234; 
       echo "1234 is an Integer in decimal notation: $a\n";
    
       $b = 0123; 
       echo "0o123 is an integer in Octal notation: $b\n";
    
       $c = 0x1A; 
       echo "0xaA is an integer in Hexadecimal notation: $c\n";
    
       $d = 0b1111;
       echo "0b1111 is an integer in binary notation: $d";
    ?>

    It will produce the following output −

    1234 is an Integer in decimal notation: 1234
    0o123 is an integer in Octal notation: 83
    0xaA is an integer in Hexadecimal notation: 26
    0b1111 is an integer in binary notation: 15
    

    PHP 7.4.0 onwards, integer literals may contain underscores (_) as separators between digits, for better readability of literals. These underscores are removed by PHP’s scanner.

    Example

    Take a look at this following example −

    <?php
       $a = 1_234_567; 
       echo "1_234_567 is an Integer with _ as separator: $a";
    ?>

    It will produce the following output −

    1_234_567 is an Integer with _ as separator: 1234567
    

    PHP does not support unsigned ints. The size of an int is platform dependent. On 32 bit systems, the maximum value is about two billion. 64-bit platforms usually have a maximum value of about 9E18.

    int size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX, and minimum value using the constant PHP_INT_MIN.

    If an integer number happens to be beyond the bounds of the int type, or any operation results in a number beyond the bounds of the int type, it will be interpreted as a float instead.

    Example

    Take a look at this following example −

    <?php
       $x = 1000000;
       $y =  50000000000000 * $x;
       var_dump($y); 
    ?>

    It will produce the following output −

    float(5.0E+19)
    

    PHP doesn’t have any operator for integer division. Hence, a division operation between an integer and a float always results in float. To obtain integral division, you may use the intval() built-in function.

    Example

    Take a look at this following example −

    <?php
       $x = 10;
       $y = 3.5;
       $z = $x/$y;
       var_dump ($z);
       $z = intdiv($x, $y);
       var_dump ($z);
    ?>

    It will produce the following output −

    float(2.857142857142857)
    int(3)