PHP – Strings

PHP – Strings ”; Previous Next A string is a sequence of characters, like ”PHP supports string operations.” A string in PHP as an array of bytes and an integer indicating the length of the buffer. In PHP, a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. PHP supports single quoted as well as double quoted string formation. Both the representations ”this is a simple string” as well as “this is a simple string” are valid. PHP also has Heredoc and Newdoc representations of string data type. Single-Quoted String A sequence of characters enclosed in single quotes (the character ”) is a string. $str = ”this is a simple string”; Example If you want to include a literal single quote, escape it with a backslash (). <?php $str = ”This is a ”simple” string”; echo $str; ?> It will give you the following output − This is a ”simple” string Example To specify a literal backslash, double it (\). <?php $str = ”The command C:\*.* will delete all files.”; echo $str; ?> Here is its output − The command C:*.* will delete all files. Example The escape sequences such as “r” or “n” will be treated literally and their special meaning will not be interpreted. The variables too will not be expanded if they appear in a single quoted string. <?php $str = ”This will not expand: n a newline”; echo $str . PHP_EOL; $x=100; $str = ”Value of x = $x”; echo $str; ?> It will produce the following output − This will not expand: n a newline Value of x = $x Double-Quoted String A sequence of characters enclosed in double-quotes (” “) is another string representation. $str = “this is a simple string”; Single-quoted and double-quoted strings are equivalent except for their treatment of escape sequences. PHP will interpret certain escape sequences for special characters. For example, “r” and “n”. Sequence Meaning n linefeed (LF or 0x0A (10) in ASCII) r carriage return (CR or 0x0D (13) in ASCII) t horizontal tab (HT or 0x09 (9) in ASCII) v vertical tab (VT or 0x0B (11) in ASCII) e escape (ESC or 0x1B (27) in ASCII) f form feed (FF or 0x0C (12) in ASCII) \ backslash $ dollar sign “ double-quote How to Escape Octal and Hexademical Characters in PHP? PHP supports escaping an Octal and a hexadecimal number to its ASCII character. For example, the ASCII character for P is 80 in decimal. 80 in decimal to Octal is 120. Similarly, 80 in decimal to hexadecimal is 50. To escape an octal character, prefix it with “”; and to escape a hexadecimal character, prefix it with “x”. <?php $str = “120110120”; echo “PHP with Octal: “. $str; echo PHP_EOL; $str = “x50x48x50”; echo “PHP with Hexadecimal: “. $str; ?> Check the output − PHP with Octal: PHP PHP with Hexadecimal: PHP As in single quoted strings, escaping any other character will result in the backslash being printed too. The most important feature of double-quoted strings is the fact that variable names will be expanded. Example A double-quoted string in PHP expands the variable names (PHP variables are prefixed with $ symbol). To actually represent a “$” symbol in a PHP string, escape it by prefixing with the “” character. <?php $price = 200; echo “Price = $ $price”; ?> You will get the following output − Price = $ 200 String Concatenation Operator To concatenate two string variables together, PHP uses the dot (.) operator − <?php $string1=”Hello World”; $string2=”1234″; echo $string1 . ” ” . $string2; ?> Here, you will get the following output − Hello World 1234 In the above example, we used the concatenation operator twice. This is because we had to insert a third string. Between the two string variables, we added a string with a single character, an empty space, to separate the two variables. The standard library of PHP includes many functions for string processing. They can be found at PHP’s official documentation (https://www.php.net/manual/en/ref.strings.php). The strlen() Function The strlen() function is used to find the length of a string. Example Let”s find the length of our string “Hello world!” − <?php echo strlen(“Hello world!”); ?> It will produce the following output − 12 The length of a string is often used in loops or other functions, when it is important to know when the string ends (that is, in a loop, we would want to stop the loop after the last character in the string). The strpos() Function The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. Example Let”s see if we can find the string “world” in our string − <?php echo strpos(“Hello world!”,”world”); ?> It will produce the following output − 6 As you can see, the position of the string “world” in our string is “6”. The reason that it is “6”, and not “7”, is that the first position in the string is

PHP – Installation

PHP – Installation ”; Previous Next You can start learning the basics of programming in PHP with the help of any of the online PHP compilers freely available on the Internet. This will help in getting acquainted with the features of PHP without installing it on your computer. Later on, install a full-fledged PHP environment on your local machine. One such online PHP compiler is provided by Tutorialpoint’s “Coding Ground for Developers”. Visit https://www.tutorialspoint.com/codingground.htm, enter PHP script and execute it. However, to be able to learn the advanced features of PHP, particularly related to the web concepts such as server variables, using backend databases, etc., you need to install the PHP environment on your local machine. In order to develop and run PHP Web pages, you neeed to install three vital components on your computer system. Web Server − PHP will work with virtually all Web Server software, including Microsoft”s Internet Information Server (IIS), NGNIX, or Lighttpd etc. The most often used web server software is the freely available Apache Server. Download Apache for free here − https://httpd.apache.org/download.cgi Database − PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. Download MySQL for free here − https://www.mysql.com/downloads/ PHP Parser − In order to process PHP script instructions a parser must be installed to generate HTML output that can be sent to the Web Browser. Although it is possible to install these three components separately, and configure the installation correctly, it is a little complex process, particularly for the beginners. Instead, using any all-in-one packaged distribution that contains precompiled Apache, MySQL and PHP binaries is convenient. XAMPP Installation There are many precompiled bundles available both in open-source as well as proprietary distributions. XAMPP, from Apache Friends (https://www.apachefriends.org/) is one of the most popular PHP enabled web server packages. We shall be using XAMPP in this tutorial. XAMPP is an easy to install Apache distribution that contains Apache, MariaDB, PHP and Perl. The letter X in the acronym indicates that it is a cross-platform software, available for use on Windows, Linux and OS X. Note that XAMPP includes MariaDB, which is a fork of MySQL, with no difference in its functionality. To download the respective installer for your operating system, visit https://www.apachefriends.org/download.html, and download one of the following − Windows − https://sourceforge.net/projects/ Linux − https://sourceforge.net/projects/ OS X − https://sourceforge.net/projects/ Using the installer on Windows is a completely wizard based installation. All you need to provide is an administrator access and the location of the installation directory which is “c:xampp” by default. To install XAMPP on Linux, use the following steps − Step 1 − Change the permissions to the installer − chmod 755 xampp-linux-*-installer.run Run the installer − sudo ./xampp-linux-*-installer.run XAMPP is now installed below the “/opt/lamp” directory. Step 2 − To start XAMPP simply call this command − sudo /opt/lampp/lampp start You should now see something like this on your screen − Starting XAMPP … LAMPP: Starting Apache… LAMPP: Starting MySQL… LAMPP started. Ready. Apache and MySQL are running. You can also use a graphical tool to manage your servers easily. You can start this tool with the following commands − cd /opt/lampp sudo ./manager-linux.run (or manager-linux-x64.run) Step 3 − To stop XAMPP simply call this command − sudo /opt/lampp/lampp stop You should now see something like this on your screen − Stopping XAMPP … LAMPP: Stopping Apache… LAMPP: Stopping MySQL… LAMPP stopped. Also, note that there is a graphical tool that you can use to start/stop your servers easily. You can start this tool with the following commands − cd /opt/lampp sudo ./manager-linux.run (or manager-linux-x64.run) If you are using OS X, follow these steps − To start the installation, Open the DMG-Image, and double-click the image to start the installation process. To start XAMPP simply open XAMPP Control and start Apache, MySQL and ProFTPD. The name of the XAMPP Control is “manager-osx”. To stop XAMPP simply open XAMPP Control and stop the servers. The name of the XAMPP Control is “manager-osx”. The XAMPP control panel is a GUI tool from which the Apache server, and MySQL can be easily started and stopped. Press the Admin button after starting the Apache module. The XAMPP homepage appears like the one shown below − PHP Parser Installation Before you proceed it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Type the following address into your browser”s address box. http://127.0.0.1/info.php If this displays a page showing your PHP installation related information then it means you have PHP and Webserver installed properly. Otherwise you have to follow given procedure to install PHP on your computer. This section will guide you to install and configure PHP over the following four platforms − PHP Installation on Linux or Unix with Apache PHP Installation on Mac OS X with Apache PHP Installation on Windows NT/2000/XP with IIS PHP Installation on Windows NT/2000/XP with Apache Apache Configuration If you are using Apache as a Web Server then this section will guide you to edit Apache Configuration Files. Just Check it here − PHP Configuration in Apache Server PHP.INI File Configuration The PHP configuration file, php.ini, is the final and most immediate way to affect PHP”s functionality. Just Check it here − PHP.INI File Configuration Windows IIS Configuration To configure IIS on your Windows machine you can refer your IIS Reference Manual shipped along with IIS. You now have a complete

PHP – File Include

PHP – File Include ”; Previous Next 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 − 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:xampphtdocstest.php on line 7 Warning: Undefined variable $lname in C:xampphtdocstest.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. Print Page Previous Next Advertisements ”;

PHP – Boolean

PHP – Boolean ”; Previous Next In PHP, “bool” is one of the built-in scalar data types. It is used to express the truth value, and it can be either True or False. A Boolean literal uses the PHP constants True or False. These constants are case-insensitive, in the sense, true, TRUE or True are synonymous. You can declare a variable of bool type as follows − $a = true; Example Logical operators (<, >, ==, !=, etc.) return Boolean values. <?php $gender=”Male”; var_dump ($gender==”Male”); ?> It will produce the following output − bool(true) Boolean Values in Control Statements Boolean values are used in the construction of control statements such as if, while, for and foreach. The behaviour of these statements depends on the true/false value returned by the Boolean operators. The following conditional statement uses the Bool value returned by the expression in the parenthesis in front of the if keyword − $mark=60; if ($mark>50) echo “pass”; else echo “fail”; Converting a Value to Boolean Use the (bool) casting operator to convert a value to bool. When a value is used in a logical context it will be automatically interpreted as a value of type bool. A non-zero number is considered as true, only 0 (+0.0 or -0.0) is false. Non-empty string represents true, empty string “” is equivalent to false. Similarly, an empty array returns false. Example Take a look at this following example − <?php $a = 10; echo “$a: “; var_dump((bool)$a); $a = 0; echo “$a: “; var_dump((bool)$a); $a = “Hello”; echo “$a: “; var_dump((bool)$a); $a = “”; echo “$a: “; var_dump((bool)$a); $a = array(); echo “$a: “; var_dump((bool)$a); ?> It will produce the following output − 10: bool(true) 0: bool(false) Hello: bool(true) : bool(false) Array: bool(false) Print Page Previous Next Advertisements ”;

PHP – Hello World

PHP – Hello World ”; Previous Next Conventionally, learners write a “Hello World” program as their first program when learning a new language or a framework. The objective is to verify if the software to be used has been installed correctly and is working as expected. To run a Hello World program in PHP, you should have installed the Apache server along with PHP module on the operating system you are using. PHP is a server-side programming language. The PHP code must be available in the document root of the web server. The web server document root is the root directory of the web server running on your system. The documents under this root are accessible to any system connected to the web server (provided the user has permissions). If a file is not under this root directory, then it cannot be accessed through the web server. In this tutorial, we are using XAMPP server software for writing PHP code. The default document root directory is typically “C:xampphtdocs” on Windows and “/opt/lamp/htdocs/” on Linux. However, you can change the default document root by modifying the DocumentRoot setting in Apache server’s configuration file “httpd.conf”. While on a Windows operating system, start the Apache server from the XAMPP control panel. Browse to the “htdocs” directory. Save the following script as “hello.php” in it. <?php echo “Hello World!”; ?> Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the “Hello World” message in the browser window. A PHP script may contain a mix of HTML and PHP code. <!DOCTYPE html> <html> <body> <h1>My PHP Website</h1> <?php echo “Hello World!”; ?> </body> </html> The “Hello World” message will be rendered as a plain text. However, you can put HTML tags inside the “Hello World” string. The browser will interpret the tags accordingly. In the following code, the “echo” statement renders “Hello World” so that it is in <h1> heading with the text aligned at the center of the page. <?php echo “<h1 align=”center”>Hello World!</h1>”; ?> PHP Script from Command Prompt You can run your PHP script from the command prompt. Let”s assume you have the following content in your “hello.php” file. <?php echo “Hello PHP!!!!!”; ?> Add the path of the PHP executable to your operating system’s path environment variable. For example, in a typical XAMPP installation on Windows, the PHP executable “php.exe” is present in “c:xamppphp” directory. Add this directory in the PATH environment variable string. Now run this script as command prompt − C:xampphtdocs>php hello.php You will get the following output − Hello PHP!!!!! Print Page Previous Next Advertisements ”;

PHP – Maths Functions

PHP – Maths Functions ”; Previous Next 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);