PHP(Personal Home Page: Hypertext Preprocessor):
PHP, short for "Personal Home Page: Hypertext Preprocessor," is a powerful open-source server-side scripting language widely used for web development. This article will guide you through the fundamentals of Core PHP, helping you build a strong foundation for creating dynamic web applications. We'll explore essential concepts, syntax, data types, operators, functions, loops, arrays, super global variables, and more.
Syntax:
PHP scripts are embedded within HTML using the PHP opening tags <?php or <? and closed with ?>. The <?= expression ?> format is used for simple echo statements.
Variables:
Variables in PHP are declared using the $ symbol. Professional practice is to use a meaningful name starting with $.

$x=12;
$y=23;
$z="hello";
$a=2.53;
$b=true;
$c=23.34e45;
var_dump($x); //int(12)
echo "<br>";
var_dump($y); //int(23)
echo "<br>";
var_dump($z); //string(5) "hello"
echo "<br>";
var_dump($a); //float(2.53)
echo "<br>";
var_dump($b); //bool(true)
echo "<br>";
var_dump($c); //float(23.34E+45)
echo "<br>";
DATA TYPES:
Data types include integers, strings, floats, booleans, arrays, objects, and resources.
Integer (2,3,5,2,35)
String "This is a Blog" or "5"
Float (.5,2.56,25.789)
Boolean TRUE or FALSE
Array Indexed array, Associative array, Multi-Dimensional array (2d-array)
Object new car(); //'car' is Class name and (new car();) is the object of 'car' class.
Resource $connection //'$connection' is a variable which holds database connectivity parameters ('server_name','database_username','database_password','database_name').
OPERATORS:
PHP provides a variety of operators for arithmetic, increment/decrement, assignment, comparison, logical, array, string, and conditional operations.
Arithematic Operators (+, -, *, /, %, **)
Increment/Decrement Operators (++$i, $i++, --$i, $i--)
Assignment Operators (+=, -=, *=, /=, %=)
Comparison Operators (==, ===, <=, >=, !=, !==, !>, !<, <>, <=>(return -1, 0, 1)(Spaceship Operator))
Logical Operators (and, or, !, &&, ||)
Array Operators (+(UNION), == (Equality), === (Identity))
String Operators (.(Temperory Append -> Concatenation Operator), .=(Permanent Append -> Concatenation Assignment Operator))
Conditional Operators ((Ternary) $x = expr1 ? expr2 : expr3, (Null Coalescing) $x = expr1 ? : expr2)
Type Operators (vardump('variable') //You can check type of any variable)
CONSTANT:
Constants are defined using define("name", "value") and are case-sensitive by default. They provide a way to store unchanging values.echo text; //The test of Universe.
define("text","The test of World.",true); //NON-Case-Sensitive
echo TEXT; or echo text; //The test of world
OUTPUT:
echo:
1) 'echo' takes single or multiple parameters for print on the browser screen.
2) 'echo' is faster than 'print'.
3) example: echo "Hello"; or echo $txt." ".$txt1;
print:
1) 'print' takes single parameter for print on browser screen.
2) 'print' slower than 'echo'.
3) example: print()
4) print also have some functions like 'print_r(expression)' for print array variable. example: print_r($car).
Control Statement:
PHP supports if, if...else, and switch conditional statements. Loops include for, while, do...while, and foreach.
//if()
if('some_condition_here')
{
//execution code
}
//if()...else
if('some_condition_here')
{
//execution code
}
else
{
//execution code
}
//if()...else if()....else if()...else or Nested if/else
if('some_condition_here')
{
//execution code
}
else if('some_condition_here')
{
if('some_condition_here')
{
//execution code
}
else
{
//execution code
}
//execution code
}
else if('some_condition_here')
{
//execution code
}
else
{
//execution code
}
LOOPS:
1) 'for' loop:
for(initialize ; condition ; increment/decrement)
{
//execution code
}
ex:
for($i=1 ; $i <= 5 ; $i++)
{
echo "This is Blog.<br>";
}
OUTPUT:
This is Blog.
This is Blog.
This is Blog.
This is Blog.
This is Blog.
2) 'while' loop:
initialize;
while(condition)
{
//execution code
increment/decrement;
}
ex:
$i=1;
while($i <= 5)
{
echo "This is Blog.<br>";
$i++;
}
OUTPUT:
This is Blog.
This is Blog.
This is Blog.
This is Blog.
This is Blog.
3) 'do{}while' loop:
initialize;
do
{
//execution code
increment/decrement;
}while(condition);
ex:
$i=1;
do
{
echo "This is Blog.<br>";
$i++;
}while($i <= 5);
OUTPUT:
This is Blog.
This is Blog.
This is Blog.
This is Blog.
This is Blog.
NOTE: * Difference between 'while(condition){}' and 'do{}while(condition)' is that, In while first check condition and then execution starts but In do while by default it executes first and then checks the condition and execute further.
4) 'foreach' loop:
In PHP, foreach loop especially used for print/display arrays and tables. It takes an argument as an array -> assign in a new variable and pass inside the loop or execution part.
foreach($current_array_variable as $new_array_variable)
{
//execution code
}
ex:
$set = array(1,2,3,4,5);
foreach($set as $row)
{
echo $row."<br>";
}
OUTPUT:
1
2
3
4
5
SWITCH CASE:
'switch' in PHP same as like in 'C/C++' programming language.
switch (variable)
{
case 'value1':
//execution code
break;
case 'value2':
//execution code
break;
(optional)
default:
//execution code
break;
}
$n=1;
switch($n)
{
case 1:
echo "This";
break;
case 2:
echo "is";
break;
case 3:
echo "Blog";
break;
}
OUTPUT:
This
FUNCTIONS:
Functions encapsulate reusable code blocks. Parameters can be optional with default values. PHP has numerous built-in functions and allows user-defined functions.
function function_name((optional parameters) = (optional type or default value))
{
//function body or execution code
}
$b = 14;
swap($a,$b);
function swap($a , $b = 3)
{
$temp = $a;
$a = $b;
$b = $temp;
echo $a." ".$b;
//here function can also return value
}
NOTE: * Here variable 'a' and 'b' both have some value, but when b not have any value then by default it takes '$b=3'.
ARRAYS:
PHP supports indexed, associative, and multi-dimensional arrays. Arrays are versatile and crucial for managing data efficiently.
1) Indexed array:
Indexed array key starts from '0' and continues with default key '0, 1, 2, 3, ......so on'.
$laptop = array(); //Initialize variable to array type
$laptop = array('dell','hp','lenovo','acer'); //Initialize and Declare array in same line.
//for print array we cn use 'print_r()'
echo "<pre>";
print_r($laptop);
OUTPUT:
[0] => dell, [1] => hp, [2] => lenovo, [3] => acer
2) Associative array:
Associative array, here we create a user define keys such as 'name' and associate with '=>' sign.
$user = array(); //Initialize variable to array type
$user = array('name'=>'Raja', 'email'=>'raja@gmail.com', 'age'=>'35'); //Initialize and Declare array in same line.
//for print array we cn use 'print_r()'
echo "<pre>";
print_r($user);
OUTPUT:
[name] => Raja, [email] => raja@gmail.com, [age] => 35
3) Multi-Dimensional array:
Multi-Dimensional array, here we create a user define keys such as 'name' and associate with '=>' sign. but here we can write array inside an array, which means a 2-D array or Multi-Dimensional array (if you remember in 'c/c++').
$user = array(); //Initialize variable to array type
$user = array('name'=>'Raja', 'email'=>'raja@gmail.com', 'address'=>array('city'=>'Indore','state'=>'Madhya Pradesh')); //Initialize and Declare array in same line.
//for print array we cn use 'print_r()'
echo "<pre>";
print_r($user);
OUTPUT:
[name] => Raja,
[email] => raja@gmail.com,
[address] => array(
[city] => Indore,
[state] => Madhya Pradesh
)
//If you want state only from array you can write this --->
echo ['address']['state'] => Madhya Pradesh //(If you remember $c[0][1] in 'c/c++').
Some Pre-defined Array Functions for Sorting (here r='descending order'):
sort() => It sort array in ascending order.
rsort() => It sort array in descending order.
asort() => It sort array in ascending order by value in an associative array.
arsort() => It sort array in descending order by value in an associative array.
ksort() => It sort array in ascending order by key in the associative array.
krsort() => It sort array in descending order by key in the associative array.
Some Pre-defined String Functions:
str_replace(str)str_shuffle(str)
strcasecmp(str1, str2)
strchr()
stripos(haystack, needle)
strlen(string)
and many more....
NOTE: * PHP have 1000+ Pre-Build functions.
SCOPES OF VARIABLES:
1) Global scope:
The variable defined inside the class or outside the function then it is called a global scope variable. but it is not accessible inside of any function, Only access given by SuperGlobal variable.
2) Local scope:
SUPER GLOBAL VARIABLES:
Super global variables like $_POST, $_GET, $_REQUEST, $_SERVER, $_FILES, $_SESSION, and $_COOKIE offer essential data to PHP scripts.
There are 8 super global variables in PHP:
1) $GLOBALS['variable']:
$GLOBALS['variable'] takes argument as an array. ex: $a=3; $GLOBALS['a']; It works when we use '$a' inside the function.
$a = 3;
valu();
function valu()
{
echo $GLOBALS['a'];
}
OUTPUT:
3
2) $_POST['variable']:
$_POST['variable'] use for collecting form data after submission with the help of method="post" (written inside form tags in html side). <input type='text' name='email'/>
$email = $_POST['email']; //'email' holds the value of input type='text' and post collect this value from email.
3) $_GET['variable']:
$_GET['variable'] use for collecting form data after submission with the help of method="get" (written inside form tags in html side). but '$_GET['var']' specialy used for get values from variable to another page.
page1:'viewtable.php'
<a href='deletepage.php?id=<?php echo $id;?>'>Delete</a> //When you click on the 'Delete' link then id sent to 'deletepage.php' page where 'id' collect by '$_GET['']' method.
page2: 'deletepage.php'
$id = $_GET['id'];
4) $_REQUEST['variable']:
$_REQUEST['variable'] use for collecting form data after submission with the help of method="post" (written inside form tags in html side). Generally '$_REQUEST['']' is not commonly used.
<input type='text' name='email'/>
$email = $_REQUEST['email']; //'email' holds the value of input type='text' and request collect this value from email.
5) $_SERVER['varaible']:
$_SERVER['varaible'] use for seeing server information. Basically, it holds information about headers, paths and scripts locations.
<form method="post" action=" "> Some input code here </form> //When we create a form, we write action which gives direction for form submission. In External PHP code, we can write external page name '%.php' AND In Internal PHP code, we can wrtie nothing and create whitespace between quotes or we can write this -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>"> Some input code here </form> //Then it execute at same page.
NOTE: * Here, 'PHP_SELF' is a pre-defined keyword of '$_SERVER['']' which gives name of current execution page.
'$_SERVER['']' also have some list of other keywords.
6) $_FILES['name_of_file']['name']:
$_FILES['name_of_file']['name'] use for file inputs only such as image/audio/video/docs/pdf...etc files. Here we write three simple line of code for files -->
<input type='file' name='img'/>
$image = $_FILES['img']['name'];
$temp_name = $_FILES['img']['tmp_name'];
move_uploaded_file($temp_name,'$img-folder/$image'); //And file upload in servers or projects folder easily.
NOTE: * Here, 'move_uploaded_file(filename, destination)' is a method used for uploading files in the projects folder with two parameters such as filename --> '$temp_name' and destination --> 'folder_name/image_file_name'.
7) $_SESSION['variable']:
$_SESSION['variable'] use for create session. but first thing is that, "What is session ?"
What is the session?
Sessions provide a straightforward mechanism for storing data specific to individual users, linked to a distinctive session ID. This functionality is invaluable for maintaining state information across multiple-page requests. Typically, session IDs are conveyed to the user's browser using session cookies, and these IDs are employed to retrieve pre-existing session data. In instances where an ID or session cookie is absent, PHP is triggered to initiate a fresh session, generating a novel session ID in the process.
In Facebook or Gmail, after logout, you cannot directly access the dashboard. you must be logged in again.
$_SESSION['userData'] = $userData;
8) $_COOKIE['variable']:
$_COOKIE['variable'] use for just print cookie value or cookie name. but first thing is that, "What is cookie ?"
What is the cookie?
PHP seamlessly integrates with HTTP cookies, a powerful tool for storing data in users' remote browsers, enabling tracking and identification of returning users. Using functions like setcookie() or setrawcookie(), cookies can be set to maintain user data. However, it's crucial to note that setcookie() should be invoked before any output is sent to the browser, similar to header(). Utilizing output buffering functions allows you to strategically control cookie and header settings, enhancing your script's efficiency and functionality.
$cookie_name = "User";
$cookie_value = "User Demo";
setcookie($cookie_name,$cookie_value, time() + (86400 * 30), "/"); //The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website.
NOTE: * You can check cookie on your system --> In Chrome, Go to browser Advanced Setting -> content setting -> Cookies -> See all cookies and site data.
IMPORT OR LINK EXTERNAL '.php' FILES:
1) include:
It includes external files which we want for some task 'include('filename')'. If file is not exist it gives error but executes further code.
2) include_once:
It just the same as include but here when we add one external file multiple times then it skips automatically and executes that file for once.3) require:
It includes external files which we want for some task 'require('filename')'. If the file does not exist it gives an error but not executes further code ("It stops whole execution").
4) require_once:
It just the same as require but here when we add one external file multiple times then it skips automatically and execute that file for once.
FOR DATE and TIME:
You can use 'date()' function like date('Y-m-d H:i:s A'). This data is with the timestamp. You can use seprate alsodate('Y-m-d') or date('H:i:s A').
NOTE: * More functions are included with 'date' in PHP.
Conclusion:
Mastering Core PHP is the foundation of successful web development. This article covered essential concepts, syntax, data types, operators, functions, loops, arrays, and super-global variables. With a strong understanding of these fundamentals, you'll be well-equipped to build dynamic and engaging web applications.
😃 Embrace the joy of coding!

Comments
Post a Comment