Author: admin

  • PHP – AJAX RSS Feed Example

    Really Simple Syndication (RSS)

    RSS, which stands for Really Simple Syndication, is used to publish often updated information from website like audio, video, images, etc. We can integrate RSS feeds to a website by using AJAX and PHP. This code demonstrates how to show RSS feeds in our site.

    Index.html

    The index page should be as follows −

    <html><head><script>
          function showRSS(str) {
             if (str.length == 0) { 
                document.getElementById("output").innerHTML = "";
                return;
             }
    
             if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
             } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
             }
             xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                   document.getElementById("output").innerHTML = xmlhttp.responseText;
                }
             }
    
             xmlhttp.open("GET","rss.php?q="+str,true);
             xmlhttp.send();
          }
       </script></head><body><p>Please Select an option to get RSS:</p><form><select onchange = "showRSS(this.value)"><option value = "">Select an RSS-feed:</option><option value = "cnn">CNN</option><option value = "bbc">BBC News</option><option value = "pc">PC World</option></select></form><br><div id = "output">RSS-feeds</div></body></html>

    rss.php

    “rss.php” has contained syntax about how to get access to RSS Feeds RSS Feeds and return RSS Feeds to the webpages.

    <?php
       $q = $_GET["q"];
    
       if($q == "cnn") {
          $xml = ("http://rss.cnn.com/rss/cnn_topstories.rss");
       } elseif($q == "bbc") {
          $xml = ("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml");
       } elseif($q = "pcw"){
          $xml = ("http://www.pcworld.com/index.rss");
       }
    
       $xmlDoc = new DOMDocument();
       $xmlDoc->load($xml);
    
       $channel = $xmlDoc->getElementsByTagName('channel')->item(0);
    
       $channel_title = $channel->getElementsByTagName('title')
       ->item(0)->childNodes->item(0)->nodeValue;
    
       $channel_link = $channel->getElementsByTagName('link')
       ->item(0)->childNodes->item(0)->nodeValue;
    
       $channel_desc = $channel->getElementsByTagName('description')
       ->item(0)->childNodes->item(0)->nodeValue;
    
       echo("<p><a href = '" . $channel_link . "'>" . 
          $channel_title . "</a>");
       echo("<br>");
       echo($channel_desc . "</p>");
    
       $x = $xmlDoc->getElementsByTagName('item');
    
       for ($i = 0; $i<=2; $i++) {
          $item_title = $x->item($i)->getElementsByTagName('title')
          ->item(0)->childNodes->item(0)->nodeValue;
    
          $item_link = $x->item($i)->getElementsByTagName('link')
          ->item(0)->childNodes->item(0)->nodeValue;
    
          $item_desc = $x->item($i)->getElementsByTagName('description')
          ->item(0)->childNodes->item(0)->nodeValue;
    
          echo ("<p><a href = '" . $item_link . "'>" . $item_title . "</a>");
          echo ("<br>");
          echo ($item_desc . "</p>");
       }
    ?>

    It will produce the following output −

    PHP RSS Feed Example
  • PHP – AJAX Auto Complete Search

    Autocomplete feature is a typeahead mechanism to show input suggestion as the user enters data in the search box provided. It is also called live search because it reacts to the users’ input. In this example, we shall use AJAX and XML parser in PHP to demonstrate the use of auto complete text box.

    This application has three main constituents −

    • The XML Document
    • JavaScript Code
    • XML Parser in PHP

    Let us now discuss these three constituents in detail −

    The XML Document

    Save the following XML script as “autocomplete.xml” in the document root folder

    <?xml version = "1.0" encoding = "utf-8"?><pages><link><title>android</title><url>https://www.tutorialspoint.com/android/index.htm</url></link><link><title>Java</title><url>https://www.tutorialspoint.com/java/index.htm</url></link><link><title>CSS </title><url>https://www.tutorialspoint.com/css/index.htm</url></link><link><title>angularjs</title><url>https://www.tutorialspoint.com/angularjs/index.htm </url></link><link><title>hadoop</title><url>https://www.tutorialspoint.com/hadoop/index.htm </url></link><link><title>swift</title><url>https://www.tutorialspoint.com/swift/index.htm </url></link><link><title>ruby</title><url>https://www.tutorialspoint.com/ruby/index.htm </url></link><link><title>nodejs</title><url>https://www.tutorialspoint.com/nodejs/index.htm </url></link></pages>

    JavaScript Code

    The following script renders a text field for the user to enter a course name of his choice. On every keystroke a JavaScript function is called, and the input value is passed to the server-side PHP script with GET method. The servers response is asynchronously rendered.

    Save this code as “index.php“.

    <html><head><script>
          function showResult(str) {
             if (str.length == 0) {
                document.getElementById("livesearch").innerHTML = "";
                document.getElementById("livesearch").style.border = "0px";
                return;
             }
    
             if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
             } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
             }
    
             xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                   document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
                   document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
                }
             }
    
             xmlhttp.open("GET","livesearch.php?q="+str,true);
             xmlhttp.send();
          }
       </script></head><body><form><h2>Enter Course Name</h2><input type = "text" size = "30" onkeyup = "showResult(this.value)"><div id = "livesearch"></div><a href = "https://www.tutorialspoint.com">More Details</a></form></body></html>

    XML Parser in PHP

    This the PHP script on the server. It parses the given XML source document, reads the characters entered in the input field, searches for it in the parsed XNL object, and sends back the response.

    Save the following code as “livesearch.php”.

    <?php
       $xml_doc = new DOMDocument();
       $xml_doc->load('autocomplete.xml');
    
       $x=$xml_doc->getElementsByTagName('link');
    
       $q = $_GET['q'];
       $result = '';
       foreach($x as $node) {
          if (stripos("{$node->nodeValue}", $q) !== false) {
             $result .= "{$node->nodeValue}";
          }
       }
    
       // Set $response to "No records found." in case no hint was found
       // or the values of the matching values
       if ($result == '')
          $result = 'No records found.';
    
       // show the results or "No records found."
       echo $result;
    ?>

    With the XAMPP server running, visit “http://localhost/index.php” and the browser displays a input text field. For each character typed in it.

  • PHP – AJAX XML Parser

    Using PHP with AJAX, we can parse an XML document from local directory as well as on a server. The following example demonstrates how to parse XML with web browser.

    The client-end script renders a HTML form and defines a JavaScript function for sending a HTTP request to the server with XMLHttpRequest object.

    On the server, a PHP script loads the DOM object from the required XML document, fetches the selected course from $_REQUEST variable, and renders the details of the course chosen as the response back to the client.

    Step 1

    The following XML document is stored on the document root of the XAMPP server.

    <?xml version = "1.0" encoding = "utf-8"?><CATALOG><SUBJECT><COURSE>Android</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$10</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Html</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$15</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Java</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$20</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Microsoft</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$25</PRICE><YEAR>2015</YEAR></SUBJECT></CATALOG>

    Step 2

    The AJAX code below has a HTML form and a JavaScript function to raise HTTP request through XMLHttpRequest object.

    <html><head><script>
          function showCD(str) {
             if (str == "") {
                document.getElementById("txtHint").innerHTML = "";
                return;
             }
    
             if (window.XMLHttpRequest) {
    		 
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
             } else {  
    		 
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
             }
    
             xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                   document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                }
             }
             xmlhttp.open("GET","hello.php?q="+str,true);
             xmlhttp.send();
          }
       </script></head><body><form>
          Select a Course:
          <select name = "cds" onchange = "showCD(this.value)"><option value = "">Select a course:</option><option value = "Android">Android </option><option value = "Html">HTML</option><option value = "Java">Java</option><option value = "Microsoft">MS technologies</option></select></form><div id = "txtHint"><b>Course info will be listed here...</b></div></body></html>

    Step 3

    The server-side PHP script to search within the XML document is as follows −

    <?php
       $q = $_GET["q"];
    
       $xmlDoc = new DOMDocument();
       $xmlDoc->load("test.xml");
    
       $x = $xmlDoc->getElementsByTagName('COURSE');
    
       for ($i = 0; $i<=$x->length-1; $i++) {
          if ($x->item($i)->nodeType == 1) {
             if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
                $y = ($x->item($i)->parentNode);
             }
          }
       }
    
       $cd = ($y->childNodes);
    
       for ($i = 0;$i<$cd->length;$i++) {
          if ($cd->item($i)->nodeType == 1) {
             echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
             echo($cd->item($i)->childNodes->item(0)->nodeValue);
             echo("<br>");
          }
       }
    ?>

    Visit “http://localhost/example.php” to let the user select a course. Upon selection, the relevant details are fetched from the server and displayed as below −

    PHP AJAX XML Parser
  • PHP – AJAX Search

    AJAX is a shortform of the term Asynchronous JavaScript and XML. Ajax is used to build fast and dynamic web pages. Below example demonstrates interaction with the backend PHP script with AJAX functions to provide a search field on the webpage.

    Step 1

    Save the following script as “example.php” −

    <html><head><style>
          span {
             color: green;
          }
       </style><script>
          function showHint(str) {
             if (str.length == 0) {
                document.getElementById("txtHint").innerHTML = "";
                return;
             } else {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function() {
                   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                      document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                   }
                }
                xmlhttp.open("GET", "hello.php?q=" + str, true);
                xmlhttp.send();
             }
          }
       </script></head><body><p><b>Search your favourite tutorials:</b></p><form><input type = "text" onkeyup = "showHint(this.value)"></form><p>Entered Course name: <span id="txtHint"></span></p></body></html>

    This code is essentially a HTML script that renders a HTML form with a text field. On its onkeyup event, a showHint() JavaScript function is called. The function sends a HTTP GET request to another PHP script on the server.

    Step 2

    Save the following script as “php_ajax.php” −

    <?php
       // Array with names
       $a[] = "Android";
       $a[] = "B programming language";
       $a[] = "C programming language";
       $a[] = "D programming language";
       $a[] = "euphoria";
       $a[] = "F#";
       $a[] = "GWT";
       $a[] = "HTML5";
       $a[] = "ibatis";
       $a[] = "Java";
       $a[] = "K programming language";
       $a[] = "Lisp";
       $a[] = "Microsoft technologies";
       $a[] = "Networking";
       $a[] = "Open Source";
       $a[] = "Prototype";
       $a[] = "QC";
       $a[] = "Restful web services";
       $a[] = "Scrum";
       $a[] = "Testing";
       $a[] = "UML";
       $a[] = "VB Script";
       $a[] = "Web Technologies";
       $a[] = "Xerox Technology";
       $a[] = "YQL";
       $a[] = "ZOPL";
    
       $q = $_REQUEST["q"];
       $hint = "";
    
       if ($q !== "") {
          $q = strtolower($q);
          $len = strlen($q);
    
          foreach($a as $name) {
             if (stristr($q, substr($name, 0, $len))) {
                if ($hint === "") {
                   $hint = $name;
                } else {
                   $hint .= ", $name";
                }
             }
          }
       }
       echo $hint === "" ? "Please enter a valid course name" : $hint;
    ?>

    Step 3

    We will start this application by opening example.php in the browser by entering the URL http://localhost/example.php

    On every keystroke in the search field, a GET request goes to the server. The server script reads the character from $_REQUEST array and searches for the course name that matches. The matched value is displayed below the text field in the browser.

    PHP AJAX Search
  • PHP – AJAX Introduction

    PHP powered web applications often make use of AJAX, together they are useful to create dynamic and interactive web applications. AJAX stands for Asynchronous Javascript and XML. It allows webpages to be updated asynchronously without reloading the entire page.

    In AJAX applications, the exchange of data between a web browser and the server-side PHP script is asynchronous. PHP is a server-side scripting language that can be used to generate dynamic content and process data.

    AJAX creates an additional layer known as AJAX engine in between the web application and web server due to which we can make background server calls using JavaScript and retrieve the required data, can update the requested portion of a web page without casing full reload of the page. It reduces the page refresh timing and provides a fast and responsive experience to the user.

    PHP AJAX Introduction

    What is Required to Run AJAX?

    The technologies that are used by AJAX are already implemented in all the Morden browsers. So the client does not require any extra module to run the AJAX application. The technologies used by AJAX are −

    • Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or we can say that it is used to create AJAX applications.
    • XML − It is used to exchange data between web server and client.
    • The XMLHttpRequest − It is used to perform asynchronous data exchange between a web browser and a web server.
    • HTML and CSS − It is used to provide markup and style to the webpage text.
    • DOM − It is used to interact with and alter the webpage layout and content dynamically.

    To use AJAX with PHP, you will need to use the XMLHttpRequest object in JavaScript to send requests to the PHP server. The PHP server will then process the request and return a response, typically in the form of JSON or XML. The JavaScript code can then parse the response and update the web page accordingly.

    The XMLHttpRequest object in JavaScript is a browser-based API that allows developers to make HTTP requests to a server without reloading the page. This is the foundation of AJAX programming, which allows for dynamic and interactive web applications.

    The XMLHttpRequest object can be used to −

    • Retrieve data from a server, such as JSON, XML, or HTML.
    • Send data to a server, such as form data or file uploads.
    • Update a web page without reloading it.
    • Create chat applications and other interactive features.

    To use the XMLHttpRequest object, you first need to create a new instance of it. Then, you can use the open() method to specify the HTTP method and request URL. Next, you can set any request headers, if needed. Finally, you can send the request using the send() method.

    Example

    Here is a simple JavaScript code of how to use the XMLHttpRequest object to retrieve data from a server −

    // Create a new XMLHttpRequest objectvar xhr =newXMLHttpRequest();// Set the HTTP method and request URL
    xhr.open("GET","test.php");// Send the request
    xhr.send();// Listen for the onload event to be fired
    xhr.onload =function(){// Check the status code to ensure the request was successfulif(xhr.status ===200){// Get the response data.var users =JSON.parse(xhr.responseText);// Do something with the user data.}else{// Handle the error}};

    The PHP script on the server retrieves the data from AJAX request and sends back the response.

    // Get the request data.$name=$_GET["name"];// Create a response object.$response=newstdClass();$response->message="Hello, $name!";// Send the response back to the client.header("Content-Type: application/json");echojson_encode($response);
  • PHP – Flash Messages

    Message flashing in a PHP web application refers to the technique that makes certain messages popup on the browser window for the user to receive applications feedback. To be able to give the user a meaningful feedback to his interactions is an important design principle, that gives a better user experience.

    In a PHP web application, we can use the session data to flash messages regarding success or failure of a certain action, notifications or warnings, etc., from time to time to keep the user informed.

    flash message allows you to create a message on one page and display it once on another page. To transfer a message from one page to another, you use the $_SESSION superglobal variable.

    To start with, you add a variable to the $_SESSION array as follows −

    <?php
       session_start();
       $_SESSION['flash_message'] = "Hello World";
    ?>

    Later, navigate to another page, and retrieve the flashed message from the $_SESSION variable and assign it to a variable. Then, you can display the message and then delete the message from the $_SESSION −

    <?php
       session_start();
       if(isset($_SESSION['flash_message'])) {
          $message = $_SESSION['flash_message'];
          unset($_SESSION['flash_message']);
          echo $message;
       }
    ?>

    To generalize the basic idea of handling the flashed messages, we shall write a function that adds a message to the $_SESSION −

    session_start();functioncreate_flash_message(string$name,string$message):void{// remove existing message with the nameif(isset($_SESSION[FLASH][$name])){unset($_SESSION[FLASH][$name]);}// add the message to the session$_SESSION[FLASH][$name]=['message'=>$message];}

    Let us also have another function that reads back a message, flashes it on the browser, and removes it from the $_SESSION.

    functiondisplay_flash_message(string$name):void{if(!isset($_SESSION[FLASH][$name])){return;}// get message from the session$flash_message=$_SESSION[FLASH][$name];// delete the flash messageunset($_SESSION[FLASH][$name]);// display the flash messageechoformat_flash_message($flash_message);}

    The format_flash_message() function applies desired formatting to the obtained string with appropriate CSS rules.

    If there are more than messages that have been flashed by the application, all of them can be retrieved and flashed with the following example −

    functiondisplay_all_flash_messages():void{if(!isset($_SESSION[FLASH])){return;}// get flash messages$flash_messages=$_SESSION[FLASH];// remove all the flash messagesunset($_SESSION[FLASH]);// show all flash messagesforeach($flash_messagesas$flash_message){echoformat_flash_message($flash_message);}}

    Use the following flash() function to create, format and flash the messages

    functionflash(string$name='',string$message=''):void{if($name!==''&&$message!==''){create_flash_message($name,$message);}elseif($name!==''&&$message===''){display_flash_message($name);// display a flash message}elseif($name===''&&$message===''){display_all_flash_messages();// display all flash message}}

    To implement the above method, call the flash() function on the first page.

    flash('first','Hello World');

    Navigate to another page and call the flash() function to retrieve and display the message −

    flash('first');

    Mechanism of using the flash messages is usually employed on a signup page to redirect users to the login page with a welcome message after they sign up.

  • PHP – File Inclusion

    When developing websites, we generally have to reuse the same information or code in many places. For example, we might want the same header, footer or menu across all pages. PHP allows us to use file inclusion instead of writing the same code many times!

    File inclusion saves time, organizes our code and allows us to make simple changes. When we make a change to one file, that changes all other files that contain that file.

    Types File Inclusion in PHP

    You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.

    This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

    The include() Function

    The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

    Syntax

    Below is the syntax of the includefunction −

    include'filename.php';

    Here, filename.php is the file you want to include. It can be a relative or absolute path.

    Example

    Assume 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>

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

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

    Output

    It will produce the following result −

    Include

    Advantages of include() Method

    Using the include() method in PHP has several advantages −

    • Adding a file allows you to reuse the same content on other pages without having to change any code.
    • You can add basic website elements like headers, footers, and menus to various pages.
    • If the included file has an error, include() will only display a warning message and the script will continue to run.
    • If you need to change the included file (for example, to update the header or footer), do so only once, and the changes will be reflected on all pages that use it.

    The require() Function

    The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

    So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

    Syntax

    Below is the syntax of the requirefunction −

    require'filename.php';

    Here, filename.php is a file you want to require. It can be a relative or absolute path.

    Example

    You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.

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

    Output

    This will produce the following result −

    This is an example to show how to include wrong PHP file!
    

    Now lets try same example with require() function.

    <?php <b>require("xxmenu.php");</b> ?><p>This is an example to show how to include wrong PHP file!</p>

    This time file execution halts and nothing is displayed.

    NOTE − You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.

    Advantages of require() Method

    Using the require() method in PHP has many advantages −

    • If the required file is important for the page (for example, a database connection file), require() makes sure the script stops and displays an error if it is not found, preventing the page from loading with limited functionality.
    • The function makes sure all necessary files are always available for proper execution. This is useful for files that the website need to work properly.
    • Like include(), require() allows you to reuse code across multiple pages.
    • With require(), you only need to include the required code once, which reduces duplication.

    Difference between include() and require() Methods

    The require statement is also used to include a file within PHP code. However, there is one important difference between include and require: if a file is included using the include line but PHP cannot find it, the script will continue to run.

    • The include() function shows a warning and continues execution if the file is missing. While the require() method shows a fatal error and stops execution if the file is missing.
    • The include() function is basically used for non-critical files for example- header, footer. While require() is used for important files like database connection, configuration.
    • The include() method can include a file multiple times unless include_once() is used. And the require() includes a file multiple times unless require_once() is used.
    • The include() continues execution even if the file is not present of missing. And require() stops script execution if the file is missing.

    The include_once() and require_once() Function

    These functions are useful when you have to make sure a file is only included once.

    // config.php
    <?php
       $database_host = 'localhost';
    ?>
    
    // settings.php
    <?php
       // Includes config.php only once   
       include_once 'config.php'; 
    
       // It will not include again if called multiple times
       require_once 'config.php'; 
       echo "Database host is: $database_host";
    ?>

    Security Risks of File Inclusion

    While file inclusion can make your code easier to work with, it may also create security risks, particularly if users have control over which files are included. This is known as Local File Inclusion (LFI) and can be used by attackers.

    Example of a Vulnerable Code

    In this scenario, a malicious user may gain access to any file on the server by changing the page query parameter, which could result in data breaches or other vulnerabilities. Here is an example code which you should avoid in your PHP applications −

    <?php
       // User can set the page parameter
       $page = $_GET['page']; 
    
       // This can lead to dangerous inclusions
       include($page); 
    ?>

    Prevent File Inclusion Vulnerabilities

    Always check and sanitize any user input before using it in an include statement.

    <?php
       $allowed_pages = ['home.php', 'about.php', 'contact.php'];
       if (in_array($page, $allowed_pages)) {
          include($page);
       } else {
          echo "Page not found.";
       }
    ?>

    Instead of including files with user-generated content you can consider using predefined paths. If you don’t need remote file inclusion so you can disable it in your php.ini file.

    allow_url_include = Off
  • PHP – 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[$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"=>"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
    

    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
    

    The 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
    )
  • PHP – Heredoc & Nowdoc

    Heredoc and Nowdoc are PHP methods that allow you to write long strings without using too many quotes or escape characters. They allow you to write multi-line strings in a neat and readable manner.

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

    Heredoc is useful for including variables, but Nowdoc is useful to get raw text without variable change.

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

  • PHP – Maths Functions

    Mathematical operations are important parts of programming. PHP has several built-in math functions that make calculations easy. These functions can be used to round numbers, find maximum and minimum values, work with exponents and logarithms and so on.

    In this chapter, we will look at different PHP math functions and mathematical (arithmetic) operators and how they can be used with the help of some examples. If you need to calculate absolute values, round numbers or perform complex mathematical operations, PHP’s math functions make it easy and efficient.

    List of Math Functions

    Here is the list of functions available in PHP −

    FunctionDescription
    abs($num)Returns the absolute (positive) value of a number.
    ceil($num)Rounds a float number up to the next highest integer.
    exp($num)Returns Euler’s number (e) raised to the power of the given number.
    floor($num)Rounds a float number down to the next lowest integer.
    intdiv($x, $y)Returns the integer quotient of two integers (ignoring remainder).
    log10($num)Returns the base-10 logarithm of a number.
    max($values)Returns the highest value from an array or multiple values.
    min($values)Returns the lowest value from an array or multiple values.
    pow($base, $exp)Returns the result of raising a number to a given power.
    round($num, $precision)Rounds a number to the nearest integer or specified decimal places.
    sqrt($num)Returns the square root of a number.

    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