Mysql Installer: Installing Mysql On Windows/ How To Get Mysql

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

Installing MySQL on Windows/ How to get MySQL

Summary: in this tutorial, you will learn step by step how to install MySQL on the Windows platform using the MySQL Installer. After the
tutorial, you will have a MySQL server and its tools up and running on your system for learning and practicing.

Download MySQL Installer


If you want to install MySQL on the Windows environment, using MySQL installer is the easiest way. MySQL installer provides you with an
easy-to-use wizard that helps you to install MySQL with the following components:

 MySQL Server

 All Available Connectors

 MySQL Workbench with Sample Data Models

 MySQL Notifier

 Tools for Excel and Microsoft Visual Studio

 MySQL Sample Databases

 MySQL Documentation

To download MySQL installer, go to the following link http://dev.mysql.com/downloads/installer/.  There are two installer files:

 If you are connecting to the internet while installing MySQL, you can choose the online installation version  mysql-installer-web-
community-<version>.exe .

 In case you want to install MySQL offline, you can download the  mysql-installer-community-<version>.exe  file.

Install MySQL via MySQL Installer


To install MySQL using the MySQL installer, double-click on the MySQL installer file and follow the steps below:

Install MySQL Step 1: Windows configures MySQL Installer

Install MySQL Step 2 – Welcome Screen: A welcome screen provides several options. Choose the first option: Install MySQL Products
Install MySQL Step 3 – Download the latest MySQL products: MySQL installer checks and downloads the latest MySQL products including
MySQL server, MySQL Workbench, etc.

Install MySQL Step 4: Click the Next button to continue


Install MySQL Step 5 – Choosing a Setup Type: there are several setup types available. Choose the Full option to install all MySQL products
and features.

Install MySQL Step 6 – Checking Requirements


Install MySQL Step 7 – Installation Progress: MySQL Installer downloads all selected products. It will take a while, depending on which
products you selected and the speed of your internet connection.

Install MySQL Step 7 – Installation Progress: downloading Products in progress.


Install MySQL Step 7 – Installation Progress: Complete Downloading. Click the Next button to continue…

Install MySQL Step 8 – Configuration Overview. Click the Next button to configure MySQL Database Server
Install MySQL Step 8.1 – MySQL Server Configuration: choose Config Type and MySQL port (3006 by default) and click Next button to
continue.

Install MySQL Step 8.1 – MySQL Server Configuration: choose a password for the root account. Please note the password download and
keep it securely if you are installing MySQL database server on a production server. If you want to add a more MySQL user, you can do it in
this step.
Install MySQL Step 8.1 – MySQL Server Configuration: choose Windows service details including Windows Service Name and account type,
then click Next button to continue.

Install MySQL Step 8.1 – MySQL Server Configuration – In Progress: MySQL Installer is configuring MySQL database server. Wait until it is
done and click the Next button to continue.
Install MySQL Step 8.1 – MySQL Server Configuration – Done. Click the Next button to continue.

Install MySQL Step 8.2 – Configuration Overview: MySQL Installer installs sample databases and sample models.
Install MySQL Step 9 – Installation Completes: the installation completes. Click the Finish button to close the installation wizard and launch
the MySQL Workbench

Basic Security Guidelines for MySQL

MySQL uses security based on Access Control Lists (ACLs) for all connections, queries, and other operations that users can attempt to perform. There is also
support for SSL-encrypted connections between MySQL clients and servers. Many of the concepts discussed here are not specific to MySQL at all; the same
general ideas apply to almost all applications.

When running MySQL, follow these guidelines:

 Do not ever give anyone (except MySQL  root  accounts) access to the  user  table in the  mysql  system database! This is critical.

 Learn how the MySQL access privilege system works (see Section 6.2, “Access Control and Account Management” ). Use
the GRANT and REVOKE statements to control access to MySQL. Do not grant more privileges than necessary. Never grant privileges to all hosts.

Checklist:

o Try mysql -u root. If you are able to connect successfully to the server without being asked for a password, anyone can connect to your MySQL
server as the MySQL root user with full privileges! Review the MySQL installation instructions, paying particular attention to the information
about setting a root password. See Section 2.10.4, “Securing the Initial MySQL Account” .

o Use the SHOW GRANTS statement to check which accounts have access to what. Then use the REVOKE statement to remove those privileges
that are not necessary.

 Do not store cleartext passwords in your database. If your computer becomes compromised, the intruder can take the full list of passwords and use
them. Instead, use SHA2() or some other one-way hashing function and store the hash value.

To prevent password recovery using rainbow tables, do not use these functions on a plain password; instead, choose some string to be used as a salt, and use
hash(hash(password)+salt) values.

 Do not choose passwords from dictionaries. Special programs exist to break passwords. Even passwords like “xfish98” are very bad. Much better
is “duag98” which contains the same word “fish” but typed one key to the left on a standard QWERTY keyboard. Another method is to use a password
that is taken from the first characters of each word in a sentence (for example, “Four score and seven years ago” results in a password of “Fsasya”). The
password is easy to remember and type, but difficult to guess for someone who does not know the sentence. In this case, you can additionally substitute
digits for the number words to obtain the phrase “4 score and 7 years ago”, yielding the password “4sa7ya” which is even more difficult to guess.

 Invest in a firewall. This protects you from at least 50% of all types of exploits in any software. Put MySQL behind the firewall or in a demilitarized zone
(DMZ).

Checklist:

o Try to scan your ports from the Internet using a tool such as nmap. MySQL uses port 3306 by default. This port should not be accessible from
untrusted hosts. As a simple way to check whether your MySQL port is open, try the following command from some remote machine,
where server_host is the host name or IP address of the host on which your MySQL server runs:

shell> telnet server_host 3306

If telnet hangs or the connection is refused, the port is blocked, which is how you want it to be. If you get a connection and some garbage characters, the port is
open, and should be closed on your firewall or router, unless you really have a good reason to keep it open.

 Applications that access MySQL should not trust any data entered by users, and should be written using proper defensive programming techniques.
See Section 6.1.7, “Client Programming Security Guidelines” .
 Do not transmit plain (unencrypted) data over the Internet. This information is accessible to everyone who has the time and ability to intercept it and
use it for their own purposes. Instead, use an encrypted protocol such as SSL or SSH. MySQL supports internal SSL connections. Another technique is to
use SSH port-forwarding to create an encrypted (and compressed) tunnel for the communication.

 Learn to use the tcpdump and strings utilities. In most cases, you can check whether MySQL data streams are unencrypted by issuing a command like
the following:

shell> tcpdump -l -i eth0 -w - src or dst port 3306 | strings

This works under Linux and should work with small modifications under other systems.

Building PHP on Windows with Apache

To install Apache with PHP 5 on Windows follow the following steps. If your PHP and Apache versions are different then please take care accordingly.

 Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension.
Double-click the installer file to install; C:\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service
or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup.

 Extract the PHP binary archive using your unzip utility; C:\PHP is a common location.

 Copy some .dll files from your PHP directory to your system directory (usually C:\Windows). You need php5ts.dll for every case. You will also probably
need to copy the file corresponding to your Web server module - C:\PHP\Sapi\php5apache.dll. to your Apache modules directory. It's possible that you
will also need others from the dlls subfolder.but start with the two mentioned previously and add more if you need them.

 Copy either php.ini-dist or php.ini-recommended (preferably the latter) to your Windows directory, and rename it php.ini. Open this file in a text editor
(for example, Notepad). Edit this file to get configuration directives; At this point, we highly recommend that new users set error reporting to E_ALL on
their development machines.

 Tell your Apache server where you want to serve files from and what extension(s) you want to identify PHP files (.php is the standard, but you can use
.html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\Program Files\Apache Group\Apache\conf or whatever your path is), and
open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both paths to the directory you want to
serve files out of. (The default is C:\Program Files\Apache Group\Apache\htdocs.). Add at least one PHP extension directive as shown in the first line of
the following code −

LoadModule php5_module modules/php5apache.dll

AddType application/x-httpd-php .php .phtml

 You may also need to add the following line −

AddModule mod_php5.c

 Stop and restart the WWW service. Go to the Start menu → Settings → Control Panel → Services. Scroll down the list to IIS Admin Service. Select it and
click Stop. After it stops, select World Wide Web Publishing Service and click Start. Stopping and restarting the service from within Internet Service
Manager will not suffice. Since this is Windows, you may also wish to reboot.

 Open a text editor. Type: <?php phpinfo(); ?>. Save this file in your Web server's document root as info.php.

 Start any Web browser and browse the file.you must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or
http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly

You should see a long table of information about your new PHP installation message Congratulations!

PHP.ini

The php.ini file is the default configuration file for running applications that require PHP. It is used to control variables such as upload sizes, file timeouts, and
resource limits.

At the time of PHP installation, php.ini is a special file provided as a default configuration file. It’s very essential configuration file which controls, what a user can
or cannot do with the website. Each time PHP is initialized, the php.ini file is read by the system. Sometimes you need to change the behavior of PHP at runtime,
then this configuration file is to use.

All the settings related to register global variables, upload maximum size, display log errors, resource limits, the maximum time to execute a PHP script and
others are written in a file as a set of directives which helps in declaring changes.

The configuration file is well commented and thorough. Keys are case sensitive, keyword values are not; whitespace, and lines beginning with semicolons are
ignored. Booleans can be represented by 1/0, Yes/No, On/Off, or True/False. The default values in php.ini-dist will result in a reasonable PHP installation that can
be tweaked later.

Configuration of php.ini file: Whenever we install PHP, we can locate the configuration file inside the PHP folder. If using xampp, we can find the configuration
file in one or many versions, inside the path ‘\xampp\php’.

Important settings or common parameters of the php.ini file:

1. enable_safe_mode = on Its default setting to ON whenever PHP is compiled. Safe mode is most relevant to CGI use.

2. register_globals = on its default setting to ON which tells that the contents of EGPCS (Environment, GET, POST, Cookie, Server) variables are registered
as global variables. But due to a security risk, the user has to ensure if it set to OFF for all scripts.

3. upload_max_filesize This setting is for the maximum allowed size for uploaded files in the scripts.

4. upload_tmp_dir = [DIR] Don’t uncomment this setting.

5. post_max_size This setting is for the maximum allowed size of POST data that PHP will accept.

6. display_errors = off This setting will not allow showing errors while running PHP project in the specified host.

7. error_reporting = E_ALL & ~E_NOTICE: This setting has default values as E_ALL and ~E_NOTICE which shows all errors except notices.
8. error_prepend_string = [“”] This setting allow you to make different color of messages.

9. max_execution_time = 30 Maximum execution time is set to seconds for any script to limit the time in production servers.

10. short_open_tags = Off To use XML functions, we have to set this option as off.

11. session.save-handler = files You don’t need to change anything in this setting.

12. variables_order = EGPCS This setting is done to set the order of variables as Environment, GET, POST, COOKIE, SERVER. The developer can change the
order as per the need also.

13. warn_plus_overloading = Off This setting issues a warning if + used with strings in a form of value.

14. gpc_order = GPC This setting has been GPC Deprecated.

15. magic_quotes_gpc = on This setting is done in case of many forms are used which submits to themselves or others and display form values.

16. magic_quotes_runtime = Off If magic_quotes_sybase is set to On, this must be Off, this setting escape quotes.

17. magic_quotes_sybase = Off If this setting is set to off it should be off, this setting escape quotes.

18. auto-prepend-file = [filepath] This setting is done when we need to automatically include() it at the beginning of every PHP file.

19. auto-append-file = [filepath] This setting is done when we need to automatically include() it at the end of every PHP file.

20. include_path = [DIR] This setting is done when we need to require files from the specified directories. Multiple directories are set using colons.

21. ignore_user_abort = [On/Off] This settings control what will happen when the user click any stop button. The default value is on this setting doesn’t
work on CGI mode it works on only module mode.

22. doc_root = [DIR] This setting is done if we want to apply PHP to a portion of our website.

23. file_uploads = [on/off] This flag is set to ON if file uploads are included in the PHP code.

24. mysql.default_host = hostname This setting is done to connect to MySQL default server if no other server host is mentioned.

25. mysql.default_user = username This setting is done to connect MySQL default username, if no other name is mentioned.

26. mysql.default_password = password This setting is done to connect MySQL default password if no other password is mentioned.

Basics of PHP

PHP or Hypertext Preprocessor is a widely used open-source general purpose scripting language and can be embedded with HTML. PHP files are saved with
“.php” extension. PHP scripts can be written anywhere in the document within PHP tags along with normal HTML.

PHP Tags or Escaping To PHP

The mechanism of separating a normal HTML from PHP code is called the mechanism of Escaping To PHP. There are various ways in which this can be done. Few
methods are already set by default but in order to use few others like Short-open or ASP-style tags we need to change the configuration of php.ini file. These
tags are also used for embedding PHP within HTML. There are 4 such tags available for this purpose:-

1. Canonical PHP Tags:The script starts with <?php and ends with ?> . These tags are also called ‘Canonical PHP tags’. Every PHP command ends with a
semi-colon (;). Let’s look at the hello world program in PHP:

<?php

# Here echo command is used to print

echo "Hello, world!";

?>

Output:

Hello, world!

2. SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The script starts with <? and ends with ?>. This will only work by
setting the short_open_tag setting in php.ini file to ‘on’.
Example:

<? 

# Here echo command will only work if 

# setting is done as said before

echo "Hello, world!";

?>
3. HTML Script Tags: These are implemented using script tags. This syntax is removed in PHP 7.0.0. so its no more used.
Example:

<script language="php">

echo "hello world!";

</script>

4. ASP Style Tags: To use this we need to set the configuration of php.ini file. These are used by Active Server Pages to describe code blocks. These starts
with <% and ends with %>.
Example:
<% 

# Can only be written if setting is turned on

# to allow %

echo "hello world";

%>

Comments in PHP

A comment is something which is ignored and not read or executed by PHP engine or the language as part of a program and is written to make the code more
readable and understandable. These are used to help other users and developers to describe the code and what it is trying to do. It can also be used in
documenting a set of code or part of a program. You must have noticed this in above sample programs.
PHP supports two types of comment:

 Single Line Comment: As the name suggests these are single line or short relevant explanations that one can add in there code. To add this, we need to
begin the line with (//) or (#).
Example:

<?php

// This is a single line comment

// These cannot be extended to more lines

  

echo "hello world!!!";

  

# This is also a single line comment

?>
Output:

hello world!!!

 Multi-line or Multiple line Comment: These are used to accomodate multiple lines with a single tag and can be extended to many lines as required by
the user. To add this, we need to begin and end the line with (/*…*/)

<?php

/* This is a multi line comment

    In PHP variables are written

    by adding a $ sign at the beginning.*/

  

$geek = "hello world!";

echo $geek;

?>

Output:

hello world!

Case Sensitivity in PHP

PHP is insensitive of whitespace. This includes all types of spaces that are invisible on the screen including tabs, spaces, and carriage return. Even one space is
equal to any numbers of spaces or carriage return. This means that PHP will ignore all the spaces or tabs in a single row or carriage return in multiple rows.
Unless a semi-colon is encountered, PHP treats multiple lines as a single command.
Example:

<?php
// PHP code illustrate the whitespace insensitivity
$var1         =     15;
$var2 =
30;
$sum = $var1
+
$var2;
  
// "\n" for new line
echo $sum, "\n";
  
$sum1 = $var1 + $var2;
echo $sum1;
?>
Output:

45

45

Here both of them show same results without any errors.

PHP is case-sensitive. All the keywords, functions and class names in PHP (while, if, echo etc) are NOT case-sensitive except variables. Only variables with
different cases are treated differently. Let’s look at this example:

<?php

// Here we can see that all echo 

// statements are executed in the same manner

   

$variable = 25;

echo $variable;

ECHO $variable;

EcHo $variable;

  

// but this line will show RUNTIME ERROR as

// "Undefined Variable"

echo $VARIABLE

?>

Output:

25

25

25

Blocks in PHP

In PHP, multiple statements can be executed simultaneously (under a single condition or loop) by using curly-braces ({}). This forms a block of statements which
gets executed simultaneously.

<?php

$var = 50;

if ($var>0){

    echo ("Positive as \n");

    echo ("greater than 0");

?>
Output:

Positive as

greater than 0

PHP Script

Standard PHP Script

A PHP script starts with the <?php and ends with the ?> tag.

The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat the enclosed code block as PHP code, rather than simple HTML.

Example

<?php

// Some code to be executed

echo "Hello, world!";

?>

Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the current statement has been reached.
Building Block of PHP

 Variables:-

Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring
and storing variables.
There are few rules, that needs to be followed and facts that need to be kept in mind while dealing with variables in PHP:
 Any variables declared in PHP must begin with a dollar sign ($), followed by the variable name.
 A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or $x)
 A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9 and ‘_’) in their name.
 Assignment of variables are done with assignment operator, “equal to (=)”. The variable names are on the left of equal and the
expression or values are to the right of the assignment operator ‘=’.
 One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers.
 PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it
automatically by analyzing the values. Same happens while conversion.
 PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.

Syntax of declaring a variable in PHP is given below:

$variablename=value;

PHP Variable: Declaring string, integer, and float


Let's see the example to store string, integer, and float values in PHP variables.
File: variable1.php
<?php  
$str="hello string";  
$x=200;  
$y=44.6;  
echo "string is: $str <br/>";  
echo "integer is: $x <br/>";  
echo "float is: $y <br/>";  
?>  
Output:
string is: hello string
integer is: 200
float is: 44.6

PHP Variable: Sum of two variables


<?php  
$x=5;  
$y=6;  
$z=$x+$y;  
echo $z;  
?>  
Output:
11

PHP Variable: case sensitive


In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR, COLor etc.
<?php  
$color="red";  
echo "My car is " . $color . "<br>";  
echo "My house is " . $COLOR . "<br>";  
echo "My boat is " . $coLOR . "<br>";  
?>  
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is

← prev

PHP Variable Scope


The scope of a variable is defined as its range in the program under which it can be accessed. In other words, "The scope of a variable is the
portion of the program within which it is defined and can be accessed."

PHP has three types of variable scopes:

1. Local variable
2. Global variable
3. Static variable

Local variable
The variables that are declared within a function are called local variables for that function. These local variables have their scope only in that
particular function in which they are declared. This means that these variables cannot be accessed outside the function, as they have local
scope.
A variable declaration outside the function with the same name is completely different from the variable declared inside the function. Let's
understand the local variables with the help of an example:

File: local_variable1.php

1. <?php  
2.     function local_var()  
3.     {  
4.         $num = 45;  //local variable  
5.         echo "Local variable declared inside the function is: ". $num;  
6.     }  
7.     local_var();  
8. ?>  

Output:

Local variable declared inside the function is: 45

File: local_variable2.php

1. <?php  
2.     function mytest()  
3.     {  
4.         $lang = "PHP";  
5.         echo "Web development language: " .$lang;  
6.     }  
7.     mytest();  
8.     //using $lang (local variable) outside the function will generate an error  
9.     echo $lang;  
10. ?>  

Output:

Web development language: PHP


Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28

Global variable
The global variables are the variables that are declared outside the function. These variables can be accessed anywhere in the program. To
access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed
or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the
function.

Let's understand the global variables with the help of an example:

Example:
File: global_variable1.php

1. <?php  
2.     $name = "Sanaya Sharma";        //Global Variable  
3.     function global_var()  
4.     {  
5.         global $name;  
6.         echo "Variable inside the function: ". $name;  
7.         echo "</br>";  
8.     }  
9.     global_var();  
10.     echo "Variable outside the function: ". $name;  
11. ?>  

Output:

Variable inside the function: Sanaya Sharma


Variable outside the function: Sanaya Sharma

Note: Without using the global keyword, if you try to access a global variable inside the function, it will generate an error that the
variable is undefined.

Example:
File: global_variable2.php

1. <?php  
2.     $name = "Sanaya Sharma";        //global variable  
3.     function global_var()  
4.     {  
5.         echo "Variable inside the function: ". $name;  
6.         echo "</br>";  
7.     }  
8.     global_var();  
9. ?>  

Output:

Notice: Undefined variable: name in D:\xampp\htdocs\program\p3.php on line 6


Variable inside the function:

Using $GLOBALS instead of global


Another way to use the global variable inside the function is predefined $GLOBALS array.

Example:

File: global_variable3.php

1. <?php  
2.     $num1 = 5;      //global variable  
3.     $num2 = 13;     //global variable  
4.     function global_var()  
5.     {  
6.             $sum = $GLOBALS['num1'] + $GLOBALS['num2'];  
7.             echo "Sum of global variables is: " .$sum;  
8.     }  
9.     global_var();  
10. ?>  

Output:

Sum of global variables is: 18

If two variables, local and global, have the same name, then the local variable has higher priority than the global variable inside the function.

Example:

File: global_variable2.php

1. <?php  
2.     $x = 5;  
3.     function mytest()  
4.     {  
5.         $x = 7;  
6.         echo "value of x: " .$x;  
7.     }  
8.     mytest();  
9. ?>  

Output:

Value of x: 7

Note: local variable has higher priority than the global variable.

Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we need to store a variable even
after completion of function execution. Therefore, another important feature of variable scoping is static variable. We use the static keyword
before the variable to define a variable, and this variable is called as static variable.

Static variables exist only in a local function, but it does not free its memory after the program execution leaves the scope. Understand it with
the help of an example:

Example:
File: static_variable.php

1. <?php  
2.     function static_var()  
3.     {  
4.         static $num1 = 3;       //static variable  
5.         $num2 = 6;          //Non-static variable  
6.         //increment in non-static variable  
7.         $num1++;  
8.         //increment in static variable  
9.         $num2++;  
10.         echo "Static: " .$num1 ."</br>";  
11.         echo "Non-static: " .$num2 ."</br>";  
12.     }  
13.       
14. //first function call  
15.     static_var();  
16.   
17.     //second function call  
18.     static_var();  
19. ?>  

Output:

Static: 4
Non-static: 7
Static: 5
Non-static: 7

You have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This is why because $num1 is not a
static variable, so it freed its memory after the execution of each function call

PHP Data Types


PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3
types:

1. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types

 Data Types

PHP Data Types: Scalar Types


It holds only single value. There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types


It can hold multiple values. There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types


There are 2 special data types in PHP.

1. resource
2. NULL

PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often used with conditional
statements. If the condition is correct, it returns TRUE otherwise FALSE.

Example:

1. <?php   
2.     if (TRUE)  
3.         echo "This condition is TRUE.";  
4.     if (FALSE)  
5.         echo "This condition is FALSE.";  
6. ?>  

Output:

This condition is TRUE.

PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without fractional part or decimal
points.

Rules for integer:

o An integer can be either positive or negative.


o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.

Example:

1. <?php   
2.     $dec1 = 34;  
3.     $oct1 = 0243;  
4.     $hexa1 = 0x45;  
5.     echo "Decimal number: " .$dec1. "</br>";  
6.     echo "Octal number: " .$oct1. "</br>";  
7.     echo "HexaDecimal number: " .$hexa1. "</br>";  
8. ?>  

Output:

Decimal number: 34
Octal number: 163
HexaDecimal number: 69

PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or decimal point, including a
negative or positive sign.

Example:

1. <?php   
2.     $n1 = 19.34;  
3.     $n2 = 54.472;  
4.     $sum = $n1 + $n2;  
5.     echo "Addition of floating numbers: " .$sum;  
6. ?>  

Output:

Addition of floating numbers: 73.812

PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.

String values must be enclosed either within single quotes or in double quotes. But both are treated differently. To clarify this, see the
example below:

Example:

1. <?php   
2.     $company = "Javatpoint";  
3.     //both single and double quote statements will treat different  
4.     echo "Hello $company";  
5.     echo "</br>";  
6.     echo 'Hello $company';  
7. ?>  

Output:

Hello Javatpoint
Hello $company

PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.

Example:

1. <?php   
2.     $bikes = array ("Royal Enfield", "Yamaha", "KTM");  
3.     var_dump($bikes);   //the var_dump() function returns the datatype and values  
4.     echo "</br>";  
5.     echo "Array Element1: $bikes[0] </br>";  
6.     echo "Array Element2: $bikes[1] </br>";  
7.     echo "Array Element3: $bikes[2] </br>";  
8. ?>  

Output:

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM

You will learn more about array in later chapters of this tutorial.

PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly declared.

Example:

1. <?php   
2.      class bike {  
3.           function model() {  
4.                $model_name = "Royal Enfield";  
5.                echo "Bike Model: " .$model_name;  
6.              }  
7.      }  
8.      $obj = new bike();  
9.      $obj -> model();  
10. ?>  

Output:

Bike Model: Royal Enfield

This is an advanced topic of PHP, which we will discuss later in detail.

PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to external PHP
resources. For example - a database call. It is an external resource.

This is an advanced topic of PHP, so we will discuss it later in detail with examples.

PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is case sensitive.

The special type of data type NULL defined a variable with no value.

Example:

1. <?php   
2.     $nl = NULL;  
3.     echo $nl;   //it will not give any output  
4. ?>  

Output:

 Operators

HP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to perform operations on variables
or values. For example:

1. $num=10+20;//+ is the operator and 10,20 are operands  

In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:

o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators

We can also categorize operators on behalf of operands. They can be categorized in 3 forms:

o Unary Operators: works on single operands such as ++, -- etc.


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction, etc. with numeric values.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

The exponentiation (**) operator has been introduced in PHP 5.6.

Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the left operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b

*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b

/= Divide then Assign $a /= $b Find quotient same as $a = $a / $b


(quotient)

%= Divide then Assign $a %= $b Find remainder same as $a = $a % $b


(remainder)

Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the evaluation and manipulation of specific
bits within the integer.

Operator Name Example Explanation

& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1

^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0.

~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1

<< Shift left $a << $b Left shift the bits of operand $a $b steps

>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places

Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison operators are given:

Operato Name Example Explanation


r

== Equal $a == $b Return TRUE if $a is equal to $b

=== Identical $a === Return TRUE if $a is equal to $b, and they are of same data type
$b

!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of same
data type

!= Not equal $a != $b Return TRUE if $a is not equal to $b

<> Not equal $a <> $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

> Greater than $a > $b Return TRUE if $a is greater than $b

<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b

>= Greater than or equal $a >= $b Return TRUE if $a is greater than or equal $b
to

<=> Spaceship $a <=>$b Return -1 if $a is less than $b


Return 0 if $a is equal $b
Return 1 if $a is greater than $b

Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.

Operator Name Example Explanation

++ Increment ++$a Increment the value of $a by one, then return $a

$a++ Return $a, then increment the value of $a by one

-- decrement --$a Decrement the value of $a by one, then return $a

$a-- Return $a, then decrement the value of $a by one

Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation and manipulation of specific
bits within the integer.

Operator Name Example Explanation

and And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true

String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP, which are given below:

Operato Name Example Explanation


r

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= First concatenate $a and $b, then assign the concatenated string
Assignment $b to $a, e.g. $a = $a . $b

Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of arrays.

Operato Name Example Explanation


r

+ Union $a + $y Union of $a and $b

== Equality $a == $b Return TRUE if $a and $b have same key/value pair

!= Inequality $a != $b Return TRUE if $a is not equal to $b

=== Identity $a === Return TRUE if $a and $b have same key/value pair of same type in same
$b order

!== Non- $a !== $b Return TRUE if $a is not identical to $b


Identity

<> Inequality $a <> $b Return TRUE if $a is not equal to $b

Type Operators
The type operator instanceof is used to determine whether an object, its parent and its derived class are the same type or not. Basically,
this operator determines which certain class the object belongs to. It is used in object-oriented programming.

1. <?php  
2.     //class declaration  
3.     class Developer  
4.     {}  
5.     class Programmer  
6.     {}  
7.     //creating an object of type Developer  
8.     $charu = new Developer();  
9.       
10.     //testing the type of object  
11.     if( $charu instanceof Developer)  
12.     {  
13.         echo "Charu is a developer.";  
14.     }  
15.     else  
16.     {     
17.         echo "Charu is a programmer.";  
18.     }  
19.     echo "</br>";  
20.     var_dump($charu instanceof Developer);           //It will return true.  
21.     var_dump($charu instanceof Programmer);       //It will return false.  
22. ?>  

Output:

Charu is a developer.
bool(true) bool(false)

Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell command. Execution operator
and shell_exec() give the same result.

Operator Name Example Explanation

`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current folder.

Note: Note that backticks (``) are not single-quotes.

Error Control Operators


PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression, any error message will be ignored that
might be generated by that expression.

Operator Name Example Explanation

@ at @file ('non_existent_file') Intentional file error

PHP Operators Precedence


Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity

clone new clone and new non-associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right

instanceof types non-associative

! logical (negation) right


*/% arithmetic left

+-. arithmetic and string concatenation left

<< >> bitwise (shift) left

< <= > >= comparison non-associative

== != === !== <> comparison non-associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= <<= >>= => assignment right

and logical left

xor logical left

or logical left

, many uses (comma) left

PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really
constants. PHP constants can be defined by 2 ways:

1. Using define() function


2. Using const keyword

Constants are similar to the variable except once they defined, they can never be undefined or changed. They remain constant across the
entire program. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

Note: Unlike variables, constants are automatically global throughout the script.

PHP constant: define()


Use the define() function to create a constant. It defines constant at run time. Let's see the syntax of define() function in PHP.

1. define(name, value, case-insensitive)  
1. name: It specifies the constant name.
2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

File: constant1.php

1. <?php  
2. define("MESSAGE","Hello JavaTpoint PHP");  
3. echo MESSAGE;  
4. ?>  
Output:

Hello JavaTpoint PHP

Create a constant with case-insensitive name:

File: constant2.php

1. <?php    
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive    
3. echo MESSAGE, "</br>";    
4. echo message;    
5. ?>    

Output:

Hello JavaTpoint PHP


Hello JavaTpoint PHP

File: constant3.php

1. <?php  
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive  
3. echo MESSAGE;  
4. echo message;  
5. ?>  

Output:

Hello JavaTpoint PHP


Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message

PHP constant: const keyword


PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a language construct, not a
function. The constant defined using const keyword are case-sensitive.

File: constant4.php

1. <?php  
2. const MESSAGE="Hello const by JavaTpoint PHP";  
3. echo MESSAGE;  
4. ?>  

Output:

Hello const by JavaTpoint PHP

Constant() function
There is another way to print the value of constants using constant() function instead of using the echo statement.

Syntax

The syntax for the following constant function:

1. constant (name)  

File: constant5.php

1. <?php      
2.     define("MSG", "JavaTpoint");  
3.     echo MSG, "</br>";  
4.     echo constant("MSG");  
5.     //both are similar  
6. ?>  

Output:

JavaTpoint
JavaTpoint

Constant vs Variables

Constant Variables
Once the constant is defined, it can never be redefined. A variable can be undefined as well as redefined easily.

A constant can only be defined using define() function. It A variable can be defined by simple assignment (=)
cannot be defined by any simple assignment. operator.

There is no need to use the dollar ($) sign before constant To declare a variable, always use the dollar ($) sign
during the assignment. before the variable.

Constants do not follow any variable scoping rules, and they Variables can be declared anywhere in the program,
can be defined and accessed anywhere. but they follow variable scoping rules.

Constants are the variables whose values can't be changed The value of the variable can be changed.
throughout the program.

By default, constants are global. Variables can be local, global, or static.

Flow Control Function

 Switching Flow:-

PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

Syntax
1. switch(expression){      
2. case value1:      
3.  //code to be executed  
4.  break;  
5. case value2:      
6.  //code to be executed  
7.  break;  
8. ......      
9. default:       
10.  code to be executed if all cases are not matched;    
11. }  
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default must always be the last statement.
2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of statement.
4. The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
PHP Switch Flowchart

PHP Switch Example


1. <?php      
2. $num=20;      
3. switch($num){      
4. case 10:      
5. echo("number is equals to 10");      
6. break;      
7. case 20:      
8. echo("number is equal to 20");      
9. break;      
10. case 30:      
11. echo("number is equal to 30");      
12. break;      
13. default:      
14. echo("number is not equal to 10, 20 or 30");      
15. }     
16. ?>  

Output:

number is equal to 20

PHP switch statement with character


Program to check Vowel and consonant

We will pass a character in switch expression to check whether it is vowel or constant. If the passed character is A, E, I, O, or U, it will be
vowel otherwise consonant.

1. <?php      
2.     $ch = 'U';  
3.     switch ($ch)  
4.     {     
5.         case 'a':   
6.             echo "Given character is vowel";  
7.             break;  
8.         case 'e':   
9.             echo "Given character is vowel";  
10.             break;  
11.         case 'i':   
12.             echo "Given character is vowel";  
13.             break;  
14.         case 'o':   
15.             echo "Given character is vowel";  
16.             break;    
17.         case 'u':   
18.             echo "Given character is vowel";  
19.             break;  
20.         case 'A':   
21.             echo "Given character is vowel";  
22.             break;  
23.         case 'E':   
24.             echo "Given character is vowel";  
25.             break;  
26.         case 'I':   
27.             echo "Given character is vowel";  
28.             break;  
29.         case 'O':   
30.             echo "Given character is vowel";  
31.             break;  
32.         case 'U':   
33.             echo "Given character is vowel";  
34.             break;  
35.         default:   
36.             echo "Given character is consonant";  
37.             break;  
38.     }  
39. ?>    

Output:

Given character is vowel

PHP switch statement with String


PHP allows to pass string in switch expression. Let's see the below example of course duration by passing string in switch case statement.

1. <?php      
2.     $ch = "B.Tech";  
3.     switch ($ch)  
4.     {     
5.         case "BCA":   
6.             echo "BCA is 3 years course";  
7.             break;  
8.         case "Bsc":   
9.             echo "Bsc is 3 years course";  
10.             break;  
11.         case "B.Tech":   
12.             echo "B.Tech is 4 years course";  
13.             break;  
14.         case "B.Arch":   
15.             echo "B.Arch is 5 years course";  
16.             break;  
17.         default:   
18.             echo "Wrong Choice";  
19.             break;  
20.     }  
21. ?>    

Output:

B.Tech is 4 years course

PHP switch statement is fall-through


PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if break statement is not found.

1. <?php      
2.     $ch = 'c';  
3.     switch ($ch)  
4.     {     
5.         case 'a':   
6.             echo "Choice a";  
7.             break;  
8.         case 'b':   
9.             echo "Choice b";  
10.             break;  
11.         case 'c':   
12.             echo "Choice c";      
13.             echo "</br>";  
14.         case 'd':   
15.             echo "Choice d";  
16.             echo "</br>";  
17.         default:   
18.             echo "case a, b, c, and d is not found";  
19.     }  
20. ?>    

Output:

Choice c
Choice d
case a, b, c, and d is not found

PHP nested switch statement


Nested switch statement means switch statement inside another switch statement. Sometimes it leads to confusion.

1. <?php      
2.     $car = "Hyundai";                   
3.         $model = "Tucson";    
4.         switch( $car )    
5.         {    
6.             case "Honda":    
7.                 switch( $model )     
8.                 {    
9.                     case "Amaze":    
10.                            echo "Honda Amaze price is 5.93 - 9.79 Lakh.";   
11.                         break;    
12.                     case "City":    
13.                            echo "Honda City price is 9.91 - 14.31 Lakh.";    
14.                         break;     
15.                 }    
16.                 break;    
17.             case "Renault":    
18.                 switch( $model )     
19.                 {    
20.                     case "Duster":    
21.                         echo "Renault Duster price is 9.15 - 14.83 L.";  
22.                         break;    
23.                     case "Kwid":    
24.                            echo "Renault Kwid price is 3.15 - 5.44 L.";  
25.                         break;    
26.                 }    
27.                 break;    
28.             case "Hyundai":    
29.                 switch( $model )     
30.                 {    
31.                     case "Creta":    
32.                         echo "Hyundai Creta price is 11.42 - 18.73 L.";  
33.                         break;    
34.         case "Tucson":    
35.                            echo "Hyundai Tucson price is 22.39 - 32.07 L.";  
36.                         break;   
37.                     case "Xcent":    
38.                            echo "Hyundai Xcent price is 6.5 - 10.05 L.";  
39.                         break;    
40.                 }    
41.                 break;     
42.         }  
43. ?>    

Output:

Hyundai Tucson price is 22.39 - 32.07 L.


 Loops

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how
many times you want to execute a block of code.

It allows users to put all the loop related statements in one place. See in the syntax given below:

Syntax
1. for(initialization; condition; increment/decrement){  
2. //code to be executed  
3. }  
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following meanings:

initialization - Initialize the loop counter value. The initial value of the for loop is done only once. This parameter is optional.

condition - Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the loop execution continues,
otherwise the execution of the loop ends.

Increment/decrement - It increments or decrements the value of the variable.

Flowchart

Example
1. <?php    
2. for($n=1;$n<=10;$n++){    
3. echo "$n<br/>";    
4. }    
5. ?>  

Output:

1
2
3
4
5
6
7
8
9
10

Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass parameters, it will execute infinite.

1. <?php  
2.     $i = 1;  
3.     //infinite loop  
4.     for (;;) {  
5.         echo $i++;  
6.         echo "</br>";  
7.     }  
8. ?>  

Output:

1
2
3
4
.
.
.

Example
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.

1. <?php  
2.     /* example 1 */  
3.   
4.     for ($i = 1; $i <= 9; $i++) {  
5.     echo $i;  
6.     }  
7.     echo "</br>";  
8.       
9.     /* example 2 */  
10.   
11.     for ($i = 1; ; $i++) {  
12.         if ($i > 9) {  
13.             break;  
14.         }  
15.         echo $i;  
16.     }  
17.     echo "</br>";  
18.       
19.     /* example 3 */  
20.   
21.     $i = 1;  
22.     for (; ; ) {  
23.         if ($i > 9) {  
24.             break;  
25.         }  
26.         echo $i;  
27.         $i++;  
28.     }  
29.     echo "</br>";  
30.       
31.     /* example 4 */  
32.   
33.     for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);  
34. ?>  

Output:

123456789
123456789
123456789
123456789

PHP Nested For Loop


We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop executes only when the outer for loop condition is
found true.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and
inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd
outer loop).

Example

1. <?php    
2. for($i=1;$i<=3;$i++){    
3. for($j=1;$j<=3;$j++){    
4. echo "$i   $j<br/>";    
5. }    
6. }    
7. ?>  

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP For Each Loop


PHP for each loop is used to traverse array elements.

Syntax

1. foreach( $array as $var ){  
2.  //code to be executed  
3. }  
4. ?>  

Example

1. <?php  
2. $season=array("summer","winter","spring","autumn");  
3. foreach( $season as $arr ){  
4.   echo "Season is: $arr<br />";  
5. }  
6. ?>  

Output:

Season is: summer


Season is: winter
Season is: spring
Season is: autumn

PHP foreach loop


The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the
variables of different datatype.

The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.

In foreach loop, we don't need to increment the value.

Syntax
1. foreach ($array as $value) {  
2.     //code to be executed  
3. }  

There is one more syntax of foreach loop.

Syntax
1. foreach ($array as $key => $element) {   
2.     //code to be executed  
3. }  
Flowchart

Example 1:
PHP program to print array elements using foreach loop.

1. <?php  
2.     //declare array  
3.     $season = array ("Summer", "Winter", "Autumn", "Rainy");  
4.       
5.     //access array elements using foreach loop  
6.     foreach ($season as $element) {  
7.         echo "$element";  
8.         echo "</br>";  
9.     }  
10. ?>  

Output:

Summer
Winter
Autumn
Rainy

Example 2:
PHP program to print associative array elements using foreach loop.

1. <?php  
2.     //declare array  
3.     $employee = array (  
4.         "Name" => "Alex",  
5.         "Email" => "alex_jtp@gmail.com",  
6.         "Age" => 21,  
7.         "Gender" => "Male"  
8.     );  
9.       
10.     //display associative array element through foreach loop  
11.     foreach ($employee as $key => $element) {  
12.         echo $key . " : " . $element;  
13.         echo "</br>";   
14.     }  
15. ?>  

Output:

Name : Alex
Email : alex_jtp@gmail.com
Age : 21
Gender : Male

Example 3:
Multi-dimensional array

1. <?php  
2.     //declare multi-dimensional array  
3.     $a = array();  
4.     $a[0][0] = "Alex";  
5.     $a[0][1] = "Bob";  
6.     $a[1][0] = "Camila";  
7.     $a[1][1] = "Denial";  
8.       
9.     //display multi-dimensional array elements through foreach loop  
10.     foreach ($a as $e1) {  
11.         foreach ($e1 as $e2) {  
12.             echo "$e2\n";  
13.         }  
14.     }  
15. ?>  

Output:

Alex Bob Camila Denial

Example 4:
Dynamic array

1. <?php  
2.     //dynamic array  
3.     foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {  
4.         echo "$elements\n";  
5.     }  
6. ?>  

Output:

j a v a t p o i n t

PHP While Loop


PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of code repeatedly until the condition is
FALSE. Once the condition gets FALSE, it exits from the body of loop.

It should be used if the number of iterations is not known.

The while loop is also called an Entry control loop because the condition is checked before entering the loop body. This means that first the
condition is checked. If the condition is true, the block of code will be executed.

Syntax
1. while(condition){  
2. //code to be executed  
3. }  
Alternative Syntax
1. while(condition):  
2. //code to be executed  
3.   
4. endwhile;  
PHP While Loop Flowchart

PHP While Loop Example


1. <?php    
2. $n=1;    
3. while($n<=10){    
4. echo "$n<br/>";    
5. $n++;    
6. }    
7. ?>  

Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example
1. <?php    
2. $n=1;    
3. while($n<=10):    
4. echo "$n<br/>";    
5. $n++;    
6. endwhile;    
7. ?>    

Output:

1
2
3
4
5
6
7
8
9
10

Example
Below is the example of printing alphabets using while loop.

1. <?php  
2.     $i = 'A';  
3.     while ($i < 'H') {  
4.         echo $i;  
5.         $i++;  
6.         echo "</br>";  
7.     }  
8. ?>  

Output:

A
B
C
D
E
F
G

PHP Nested While Loop


We can use while loop inside another while loop in PHP, it is known as nested while loop.

In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3
times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and
3 times for 3rd outer loop).

Example

1. <?php    
2. $i=1;    
3. while($i<=3){    
4. $j=1;    
5. while($j<=3){    
6. echo "$i   $j<br/>";    
7. $j++;    
8. }    
9. $i++;    
10. }    
11. ?>    

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP Infinite While Loop


If we pass TRUE in while loop, it will be an infinite loop.

Syntax

1. while(true) {    
2. //code to be executed    
3. }    

Example

1. <?php  
2.     while (true) {  
3.         echo "Hello Javatpoint!";  
4.         echo "</br>";  
5.     }  
6. ?>  

Output:

Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
.
.
.
.
.
Hello Javatpoint!
Hello Javatpoint!

PHP do-while loop


PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.

The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the loop at least once and the
number of iterations is not even fixed, it is recommended to use the do-while loop.

It executes the code at least one time always because the condition is checked after executing the code.

The do-while loop is very much similar to the while loop except the condition check. The main difference between both loops is that while loop
checks the condition at the beginning, whereas do-while loop checks the condition at the end of the loop.

Syntax
1. do{  
2. //code to be executed  
3. }while(condition);  
Flowchart

Example
1. <?php    
2. $n=1;    
3. do{    
4. echo "$n<br/>";    
5. $n++;    
6. }while($n<=10);    
7. ?>    

Output:

1
2
3
4
5
6
7
8
9
10

Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is must that the program should
not contain any other statements after the do-while loop. In this case, it will not generate any error.

1.  <?php  
2.     $x = 5;  
3.     do {  
4.         echo "Welcome to javatpoint! </br>";  
5.         $x++;  
6.     } while ($x < 10);  
7. ?>  

Output:

Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!

Example
The following example will increment the value of $x at least once. Because the given condition is false.

1.  <?php  
2.     $x = 1;  
3.     do {  
4.         echo "1 is not greater than 10.";  
5.         echo "</br>";  
6.         $x++;  
7.     } while ($x > 10);  
8.     echo $x;  
9. ?>  

Output:

1 is not greater than 10.


2

Difference between while and do-while loop

while Loop do-while loop

The while loop is also named as entry control loop. The do-while loop is also named as exit control loop.

The body of the loop does not execute if the condition The body of the loop executes at least once, even if the
is false. condition is false.

Condition checks first, and then block of statements Block of statements executes first and then condition checks.
executes.

This loop does not use a semicolon to terminate the Do-while loop use semicolon to terminate the loop.
loop.
CHAPTER 2
Basic Working
Functions:-

What is Function?
A function is a block of code written in a program to perform some specific task. We can relate functions in programs to employees in a office in real life
for a better understanding of how functions work. Suppose the boss wants his employee to calculate the annual budget. So how will this process
complete? The employee will take information about the statics from the boss, performs calculations and calculate the budget and shows the result to
his boss. Functions works in a similar manner. They take informations as parameter, executes a block of statements or perform operations on this
parameters and returns the result.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of function, you can write the logic only once and
reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application because every logic is
divided in the form of functions.

PHP provides us with two major types of functions:


 Built-in functions : PHP provides us with huge collection of built-in library functions. These functions are already coded and stored in form of functions.
To use those we just need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.
 User Defined Functions : Apart from the built-in functions, PHP allows us to create our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply calling it.

We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined functions.

Syntax
1. function functionname(){  
2. //code to be executed  
3. }  

Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be start with numbers or special
symbols.

PHP Functions Example


File: function1.php

1. <?php  
2. function sayHello(){  
3. echo "Hello PHP Function";  
4. }  
5. sayHello();//calling function  
6. ?>  

Output:

Hello PHP Function

PHP Function Arguments


We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length argument list.

Let's see the example to pass single argument in PHP function.

File: functionarg.php

1. <?php  
2. function sayHello($name){  
3. echo "Hello $name<br/>";  
4. }  
5. sayHello("Sonoo");  
6. sayHello("Vimal");  
7. sayHello("John");  
8. ?>  

Output:

Hello Sonoo
Hello Vimal
Hello John

Let's see the example to pass two argument in PHP function.


File: functionarg2.php

1. <?php  
2. function sayHello($name,$age){  
3. echo "Hello $name, you are $age years old<br/>";  
4. }  
5. sayHello("Sonoo",27);  
6. sayHello("Vimal",29);  
7. sayHello("John",23);  
8. ?>  

Output:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call by value). But we can do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you need to use ampersand (&) symbol before the
argument name.

Let's see a simple example of call by reference in PHP.

File: functionref.php

1. <?php  
2. function adder(&$str2)  
3. {  
4.     $str2 .= 'Call By Reference';  
5. }  
6. $str = 'Hello ';  
7. adder($str);  
8. echo $str;  
9. ?>  

Output:

Hello Call By Reference

PHP Function: Default Argument Value


We can specify a default argument value in function. While calling PHP function if you don't specify any argument, it will take the default
argument. Let's see a simple example of using default argument value in PHP function.

File: functiondefaultarg.php

1. <?php  
2. function sayHello($name="Sonoo"){  
3. echo "Hello $name<br/>";  
4. }  
5. sayHello("Rajesh");  
6. sayHello();//passing no value  
7. sayHello("John");  
8. ?>  

Output:

Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value


Let's see an example of PHP function that returns value.

File: functiondefaultarg.php

1. <?php  
2. function cube($n){  
3. return $n*$n*$n;  
4. }  
5. echo "Cube of 3 is: ".cube(3);  
6. ?>  

Output:

Cube of 3 is: 27
Array

What is Array?

Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving
us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be
accessed using their index or key. Suppose we want to store five names and print them accordingly. This can be easily done by the use of five
different string variables. But if instead of five, the number rises to hundred, then it would be really difficult for the user or developer to
create so much different variables. Here array comes into play and helps us to store every element within a single variable and also allows
easy access using an index or a key. An array is created using an array() function in PHP.

Advantage of PHP Array

Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are
assigned to an index number by default.

There are two ways to define indexed array:

1st way:

1. $season=array("summer","winter","spring","autumn");  

2nd way:

1. $season[0]="summer";  
2. $season[1]="winter";  
3. $season[2]="spring";  
4. $season[3]="autumn";  

Example
File: array1.php

1. <?php  
2. $season=array("summer","winter","spring","autumn");  
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
4. ?>  

Output:

Season are: summer, winter, spring and autumn

File: array2.php

1. <?php  
2. $season[0]="summer";  
3. $season[1]="winter";  
4. $season[2]="spring";  
5. $season[3]="autumn";  
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
7. ?>  

Output:

Season are: summer, winter, spring and autumn

Click me for more details...

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:


1st way:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");  

2nd way:

1. $salary["Sonoo"]="350000";  
2. $salary["John"]="450000";  
3. $salary["Kartik"]="200000";  

Example
File: arrayassociative1.php

1. <?php    
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
4. echo "John salary: ".$salary["John"]."<br/>";  
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
6. ?>    

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php

1. <?php    
2. $salary["Sonoo"]="350000";    
3. $salary["John"]="450000";    
4. $salary["Kartik"]="200000";    
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
6. echo "John salary: ".$salary["John"]."<br/>";  
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
8. ?>    

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can
be represented in the form of matrix which is represented by row * column.

Definition
1. $emp = array  
2.   (  
3.   array(1,"sonoo",400000),  
4.   array(2,"john",500000),  
5.   array(3,"rahul",300000)  
6.   );  

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3
columns.

Id Name Salary

1 sonoo 400000

2 john 500000

3 rahul 300000

File: multiarray.php

1. <?php    
2. $emp = array  
3.   (  
4.   array(1,"sonoo",400000),  
5.   array(2,"john",500000),  
6.   array(3,"rahul",300000)  
7.   );  
8.   
9. for ($row = 0; $row < 3; $row++) {  
10.   for ($col = 0; $col < 3; $col++) {  
11.     echo $emp[$row][$col]."  ";  
12.   }  
13.   echo "<br/>";  
14. }  
15. ?>    

Output:

1 sonoo 400000
2 john 500000
3 rahul 300000

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are given below.

1) PHP array() function


PHP array() function creates and returns an array. It allows you to create indexed, associative and multidimensional arrays.

Syntax

1. array array ([ mixed $... ] )  

Example

1. <?php    
2. $season=array("summer","winter","spring","autumn");    
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";    
4. ?>    

Output:

Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function


PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )  

Example

1. <?php    
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
3. print_r(array_change_key_case($salary,CASE_UPPER));   
4. ?>    

Output:

Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

Example

1. <?php    
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
3. print_r(array_change_key_case($salary,CASE_LOWER));   
4. ?>    

Output:

Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )

3) PHP array_chunk() function


PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide array into many parts.
Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )  

Example

1. <?php    
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
3. print_r(array_chunk($salary,2));   
4. ?>    

Output:

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

4) PHP count() function


PHP count() function counts all elements in an array.

Syntax

1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )  

Example

1. <?php    
2. $season=array("summer","winter","spring","autumn");    
3. echo count($season);    
4. ?>    

Output:

5) PHP sort() function


PHP sort() function sorts all the elements in an array.

Syntax

1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  

Example

1. <?php    
2. $season=array("summer","winter","spring","autumn");    
3. sort($season);  
4. foreach( $season as $s )    
5. {    
6.   echo "$s<br />";    
7. }    
8. ?>    

Output:

autumn
spring
summer
winter

6) PHP array_reverse() function


PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )  

Example

1. <?php    
2. $season=array("summer","winter","spring","autumn");    
3. $reverseseason=array_reverse($season);  
4. foreach( $reverseseason as $s )    
5. {    
6.   echo "$s<br />";    
7. }    
8. ?>    

Output:

autumn
spring
winter
summer

7) PHP array_search() function


PHP array_search() function searches the specified value in an array. It returns key if search is successful.

Syntax

1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )  

Example

1. <?php    
2. $season=array("summer","winter","spring","autumn");    
3. $key=array_search("spring",$season);  
4. echo $key;    
5. ?>    

Output:

8) PHP array_intersect() function


PHP array_intersect() function returns the intersection of two array. In other words, it returns the matching elements of two array.

Syntax

1. array array_intersect ( array $array1 , array $array2 [, array $... ] )  

Example

1. <?php    
2. $name1=array("sonoo","john","vivek","smith");    
3. $name2=array("umesh","sonoo","kartik","smith");    
4. $name3=array_intersect($name1,$name2);  
5. foreach( $name3 as $n )    
6. {    
7.   echo "$n<br />";    
8. }    
9. ?>    

Output:

sonoo
smith

Object

PHP | Objects

An Object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to it. Objects are also
known as instances.

Creating an Object:
Following is an example of how to create object using new operator.

class Books {

// Members of class Books

// Creating three objects of Books

$physics = new Books;

$maths = new Books;

$chemistry = new Books;

Member Functions:
After creating our objects, we can call member functions related to that object. A member function typically accesses members of current object only.
Example:

$physics->setTitle( "Physics for High School" );

$chemistry->setTitle( "Advanced Chemistry" );

$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );

$chemistry->setPrice( 15 );

$maths->setPrice( 7 );

The following syntax used are for the following program elaborated in the example given below:

Example:

<?php
   class Books {
  
      /* Member variables */
      var $price;
      var $title;
        
      /* Member functions */
      function setPrice($par){
         $this->price = $par;
      }
        
      function getPrice(){
         echo $this->price."<br>";
      }
        
      function setTitle($par){
         $this->title = $par;
      }
        
      function getTitle(){
         echo $this->title."<br>" ;
      }
   }
  
   /* Creating New object using "new" operator */
   $maths = new Books;
  
   /* Setting title and prices for the object */
   $maths->setTitle( "Algebra" );
   $maths->setPrice( 7 );
  
   /* Calling Member Functions */  
   $maths->getTitle();
   $maths->getPrice();
?>

How to change date format in PHP?


To convert the date-time format PHP provides strtotime() and date() function. We change the date format from one format to another. For
example - we have stored date in MM-DD-YYYY format in a variable, and we want to change it to DD-MM-YYYY format.

We can achieve this conversion by using strtotime() and date() function. These are the built-in functions of PHP. The strtotime() first converts
the date into the seconds, and then date() function is used to reconstruct the date in any format. Below some examples are given to convert
the date format.

Change YYYY-MM-DD to DD-MM-YYYY


In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format.

1. <?php  
2.     $orgDate = "2019-09-15";  
3.     $newDate = date("d-m-Y", strtotime($orgDate));  
4.     echo "New date format is: ".$newDate. " (MM-DD-YYYY)";  
5. ?>  

Output
New date format is: 15-09-2019 (DD-MM-YYYY)

Change YYYY-MM-DD to MM-DD-YYYY


In the below example, we have date 2019-02-26 in YYYY-MM-DD format, and we will convert this to 02-26-2019 (MM-DD-YYYY) format.

1. <?php  
2.     $orgDate = "2019-02-26";  
3.     $newDate = date("m-d-Y", strtotime($orgDate));  
4.     echo "New date format is: ".$newDate. " (MM-DD-YYYY)";  
5. ?>  

Output

New date format is: 02-26-2019 (MM-DD-YYYY)

Change DD-MM-YYYY to YYYY-MM-DD


In the below example, we have date 17-07-2012 in DD-MM-YYYY format, and we will convert this to 2012-07-17 (YYYY-MM-DD) format.

1. <?php  
2.     $orgDate = "17-07-2012";  
3.     $newDate = date("Y-m-d", strtotime($orgDate));  
4.     echo "New date format is: ".$newDate. " (YYYY-MM-DD)";  
5. ?>  

Output

New date format is: 2012-07-17 (YYYY-MM-DD)

Change DD-MM-YYYY to YYYY/MM/DD


Suppose we have date 17-07-2012 in DD-MM-YYYY format separated by dash (-) sign. We want to convert this to 2012/07/17 (YYYY/MM/DD)
format, which will be separated by the slash (/). In the below example, DD-MM-YYYY format is converted to the YYYY-MM-DD format, and
also dashes (-) will be replaced with slash (/) sign.

1. <?php  
2.     $orgDate = "17-07-2012";  
3.     $date = str_replace('-"', '/', $orgDate);  
4.     $newDate = date("Y/m/d", strtotime($date));  
5.     echo "New date format is: ".$newDate. " (YYYY/MM/DD)";  
6. ?>  

Output

date format is: 2012/07/17 (YYYY/MM/DD)

Change date time to another format


Here in the below example, we will convert the date format MM-DD-YYYY to YYYY-DD-MM format and 12 hours time clock to 24 hours time
clock.

1. <?php  
2.     $date = "06/13/2019 5:35 PM";  
3.     //converts date and time to seconds  
4.     $sec = strtotime($date);  
5.     //converts seconds into a specific format  
6.     $newdate = date ("Y/d/m H:i", $sec);  
7.     //Appends seconds with the time  
8.     $newdate = $newdate . ":00";  
9.     // display converted date and time  
10.     echo "New date time format is: ".$newDate;  
11. ?>  

Output

New date time format is: 2019/13/06 17:35:00

Manipulating PHP Strings


PHP provides many built-in functions for manipulating strings like calculating the length of a string, find substrings or
characters, replacing part of a string with different characters, take a string apart, and many others. Here are the examples of
some of these functions.

Investigating Strings with PHP

strlen($str)
This function returns the length of the string or the number of characters in the string including whitespaces.
<?php

$str = "Welcome to Studytonight";

// using strlen in echo method

echo "Length of the string is: ". strlen($str);

?>

Length of the string is: 23

str_word_count($str)
This function returns the number of words in the string. This function comes in handly in form field validation for some simple
validations.
<?php

$str = "Welcome to Studytonight";

// using str_word_count in echo method

echo "Number of words in the string are: ". str_word_count($str);

?>

Number of words in the string are: 3

strrev($str)
This function is used to reverse a string.
Let's take an example and see,
<?php

$str = "Welcome to Studytonight";

// using strrev in echo method

echo "Reverse: ". strrev($str);

?>

Reverse: thginotydutS ot emocleW

strpos($str, $text)
This function is used to find the position of any text/word in a given string. Just like an array, string also assign index value to the
characters stored in it, starting from zero.
<?php

$str = "Welcome to Studytonight";

// using strpos in echo method

echo "Position of 'Studytonight' in string: ". strpos($str, 'Studytonight');

?>

Position of 'Studytonight' in string: 11

str_replace($replacethis, $replacewith, $str)


This function is used to replace a part of the string with some text. While using this function, the first argument is the part of string that
you want to replace, second argument is the new text you want to include, and the last argument is the string variable itself.
Let's take an example,
<?php

$str = str_replace("Studytonight", "Studytonight.com", "Welcome to Studytonight");

echo $str;

?>

Welcome to Studytonight.com

ucwords($str)
This function is used for formatting the string. This function converts first letter/character of every word in the string to uppercase.
Let's take an example and see,
<?php

$str = "welcome to studytonight";

echo ucwords($str);

?>

Welcome To Studytonight

strtoupper($str)
To convert every letter/character of every word of the string to uppercase, one can use strtoupper() method.
<?php

$str = "welcome to studytonight";

echo strtoupper($str);

?>

WELCOME TO STUDYTONIGHT
strtolower($str)
This function is used to convert every letter/character of a string to lowercase.
<?php

$str = "WELCOME TO STUDYTONIGHT";

echo strtolower($str);

?>

welcome to studytonight

str_repeat($str, $counter)
This function is used to repeat a string a given number of times. The first argument is the string and the second argument is the number
of times the string should be repeated.
<?php

$str = "Studytonight";

echo str_repeat($str, 4);

?>

StudytonightStudytonightStudytonightStudytonight

strcmp($str1, $str2)
This function is used to compare two strings. The comparison is done alphabetically. If the first string is greater than second string, the
result will be greater than 0, if the first string is equal to the second string, the result will be equal to 0 and if the second string is greater
than the first string, then the result will be less than 0.
<?php

$str1 = "Studytonight";

$str2 = "Studytonight.com";

// comparing str1 and str2

echo strcmp($str1, $str2);

// comparing str2 and str1

echo strcmp($str2, $str1);

// comparing str1 with str1

echo strcmp($str1, $str1);

?>

-4

0
substr($str, $start, $length)
This function is used to take out a part of the string(substring), starting from a particular position, of a particular length.
The first argument is the string itself, second argument is the starting index of the substring to be exracted and the third argument is the
length of the substring to be extracted.
<?php

$str = "Welcome to Studytonight";

echo substr($str, 11, 12);

?>

Studytonight

trim($str, charlist)
This function is used to remove extra whitespaces from beginning and the end of a string. The second argument charlist is optional.
We can provide a list of character, just like a string, as the second argument, to trim/remove those characters from the main string.
<?php

$str1 = " Hello World ";

echo trim($str1) . "<br/>";

$str2 = "Hello Hello";

echo trim($str2,"Heo");

?>

Hello World

llo Hell

As you can see in the output, additional spaces from the beginning and end are removed and in the second case, the characters
specified are removed from the beginning and the end of the string.

explode(separator, $str, $limit)


This function is used to break a string, create an array of the broken parts of the string and return the array. The first
argument, separator defines where to break the string from. It can be a space, hiphen(-) or any other character.
The second argument of this function is the string itself and the third argument is the limit, which specifies the number of array
elements to return. the third argument is optional.
Let's have an example,
<?php

$str = "Its a beautiful day";

// we can directly print the result of explode

print_r(explode(" ", $str));

?>

Array (
[0] => Its

[1] => a

[2] => beautiful

[3] => day

In the example above, we have provided space as separator to break the string and return an array.
If we provide the third argument limit as well, we can limit the number of array elements returned. For example, if we provide 2 as the
third argument, then we will only get 2 elements in the array, the first two.

implode(separator, $arr)
This function is used to form a string using the array elements from the array provided and join them using the separator.
Let's take an example,
<?php

$arr = array("Its", "a", "beautiful", "day");

// <br> is used to jump to next line

echo implode(" ", $arr) . "<br>";

echo implode("-", $arr) . "<br>";

echo implode("/", $arr) . "<br>";

?>

Its a beautiful day

Its-a-beautiful-day

Its/a/beautiful/day

nl2br($str)
This function is used to change line break or \n to the HTML tag for line break, which is <br>.
This function is very useful to format string data to display on HTML pages because when a multiline form data is submitted, it
has \n included in the strnig for line breaks, but when you display it on your HTML page, the line breaks will not get rendered because
HTML doesn't understand \n.
<?php

echo nl2br("Its a\nbeautiful day");

?>

Its a

beautiful day

Working with Forms

Create a login Page


<html>
<head>
<title>My First PHP Program!</title>
</head>

<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<p>username <input type="text" name="usser"/></p>
<p>password <input type="password" name="pass" /></p>
<p> <input type="submit" name="submit" /></p>
</form>
<?php
$name = $_REQUEST['usser'];
$pas=$_REQUEST['pass'];
if($name=="mandeep"&&$pas=="mani"){
echo "successful";
}
else{
echo "Login Failed";
}
?>
</body>
</html>

Understanding How HTML Form Works


Let's create a simple HTML form and try to understand how it works, what are the different attributes available in the <form> tag and
what are they used for.
<html>

<body>

<form action="form-handler.php" method="POST">

Name: <input type="text" name="name"> <br/>

Email: <input type="text" name="email"> <br/>

<input type="submit">

</form>

</body>

</html>

In the code above, we have used the <form> tag to create an HTML form, with input fields for Name and Email along with submit button
to submit the form-data.
In the <form> tag, we have two attributes, action and method, do you know what they are for?

1. action: Using this attribute, we can specify the name of the file which will collect and handle the form-data. In the example above, we have

provided name of a Php file.

2. method: This attribute specify the means of sending the form-data, whether it will be submitted via POST method or GET method.

Below we have the same form with method as GET,


<html>

<body>

<form action="form-handler.php" method="GET">

Name: <input type="text" name="name"> <br/>

Email: <input type="text" name="email"> <br/>

<input type="submit">

</form>

</body>

</html>

PHP Form Handling with POST


If we specify the form method to be POST, then the form-data is sent to the server using the HTTP POST method.
Below, we have the code, to access the form-data in the Php file specified in the action attribute of our HTML form.
<?php

// getting the value of name field


$name = $_POST["name"];

// getting the value of the email field

$email = $_POST["email"];

echo "Hi, ". $name . "<br>";

echo "Your email address: ". $email ."<br>";

?>

Hi, Studytonight

Your email address: we@studytonight.com

You will get the above output, if you provide name as "Studytonight" and email address as "we@studytonight.com".

PHP Form Handling with GET


If we specify the form method to be GET, then the form-data is sent to the server using the HTTP GET method.
Below, we have the code, to access the form-data in the Php file specified in the action attribute of our HTML form, this time using the
GET superglobal.
<?php

// getting the value of name field

$name = $_GET["name"];

// getting the value of the email field

$email = $_GET["email"];

echo "Hi, ". $name . "<br>";

echo "Your email address: ". $email ."<br>";

?>

Hi, Studytonight

Your email address: we@studytonight.com

Again, the output remains the same.


The first step to process the form-data is to fetch the data using POST or GET superglobals, once you have the data, you can do
anything with it, display it on your webpage, save the data into database, perform validations etc.
GET vs. POST: When to use What!
Now, you must be wondering, which one should we use. Well, both GET and POST are used for the same purpose but they work
differently.
When a user submits a form, the values from the input fields are stored in an array, like array(key1=>value1, key2=>value2,...) and
then passed on to the destination(Php file) specified in the action attribute of the <form> tag.

Using GET method


In case of GET method, form-data is submitted as URL parameters, i.e. all the values entered in the form fields by the user are sent to
the action script, appended in the URL.
Let's take a simple example to understand, below we have a simple HTML form,
<html>

<body>

<form action="form-handler.php" method="GET">

Name: <input type="text" name="name"> <br/>

Age: <input type="text" name="age"> <br/>

<input type="submit">

</form>

</body>

</html>

We have two input fields in above form, one is name and the other one is age. When we click on submit, we will be redicrected to the
following URL, form-handler.php?name=Studytonight&age=5, with the form-data appended to the URL.
Sending the form-data as URL parameters proves out useful at times as you can easily bookmark links with form-data, but for
appending parameters in a URL there is a limit of 2000 characters, hence for forms with large number of fields, it is not suggested, as
some data might get lost or the form submission may lead to error.
The Php file form-handler.php will look like,
<?php

// name attribute of the input field goes inside the

// square brackets of $_GET superglobal

$name = $_GET["name"];

$age = $_GET["age"];

echo "Your name is ". $name . " and you are ". $age . " years old".

?>

Your name is Studytonight and you are 5 years old

As the form-data is visible to everyone because it sent as URL parameters, hence we should not use GET method for a form
with sensitive data, like passwords etc.

Using POST method


When we use the POST method, the array of key-value pair(the form-data), coming from the HTML form are sent as part of the HTTP
request, hence they are invisible to the user.
Also, there is no character limit for the information/data being transmitted.
POST method also supports multipart form-data upload which is used for file upload.
We would recommend, that you use the POST method while working on any PHP web application/project.
Let's take a simple example to understand, below we have a simple HTML form,
<html>

<body>
<form action="form-handler.php" method="POST">

Name: <input type="text" name="name"> <br/>

Age: <input type="text" name="age"> <br/>

<input type="submit">

</form>

</body>

</html>

The Php file form-handler.php will look like,


<?php

// name attribute of the input field goes inside the

// square brackets of $_POST superglobal

$name = $_POST["name"];

$age = $_POST["age"];

echo "Your name is ". $name . " and you are ". $age . " years old".

?>

Your name is Studytonight and you are 5 years old

You might also like