Welcome to PHP, Part 1
What is PHP? It is a server-side scripting language
Why should I learn PHP in 2020?
People are moving to GoLang, Swift, Ruby, Rust etc and then why to learn PHP in 2020? Okay there are plenty of reasons to learn php in 2020. PHP stands for “PHP hypertext Preprocessor” which was created in 1995 by Rasmus Lerdorf using “C” and it is server-side scripting language. Following are the reasons to learn php,
- It is still on top 10 Programming languages.
- It has faster learning curve and easy for scaling web applications.
- More than 50% of websites are on PHP including Facebook, Wikipedia, Yahoo and lot.
- It is a general purpose language which can use for Machine Learning, Artificial Intelligence, Mobile application development and even in serverless.
- It has a large number of community.
Quick tip: Install Xampp if you need to install php because it comes with apache and mysql which will be easier.
Let’s start with PHP
In this series I am going to talk about on following topics.
- Welcome to PHP, part 1 — PHP basics including variables, conditional statements, loops, functions
- Welcome to PHP, part 2 — Create a dynamic website with Mysql
- Welcome to PHP, part 3 — Dockerize your application with Nginx.
Variables in php
There are several conventions you have to follow when you make variables as follows.
- It should start with “$” followed by the name.
- The variable name should starts with either a letter or the underscore “_”.
- Variables should only consists of alphanumeric characters and underscore.
Boolean
Boolean can be defined as follows and there are only two values can be assigned which are true and false.
$hasEnded = true;
There are three operations for booleans which are NOT, AND, OR and XOR operations.
NOT operator — This will return the opposite value of the boolean. The symbol used is “!”.
$hasEnded = true;
if(!$hasEnded){ // !$hasEnded = false
// Do something.
}
AND operator — This will return true only if both conditions are true. There are two ways of using this by either “and” or “&&”.
$hasEnded = true;
$hasMoney = true;
if($hasEnded and $hasMoney){ // true and true -> true
// Do something.
}
if($hasEnded && !$hasMoney){ // true and not(true) -> false
// Do something.
}
OR operator — This will return true if either condition is true. There are two ways of using this by either “or” or “||”.
$hasEnded = true;
$hasMoney = true;
if($hasEnded or $hasMoney){ // true and true -> true
// Do something.
}
if($hasEnded || !$hasMoney){ // true and not(true) -> true
// Do something.
}
if(!$hasEnded or !$hasMoney){ // not(true) and not(true) -> false
// Do something.
}
XOR — This will return true if either condition is true but not both. The symbol used is “xor”.
$hasEnded = true;
$hasMoney = true;
if($hasEnded xor $hasMoney){ // true and true -> false
// Do something.
}
if($hasEnded xor !$hasMoney){ // true and not(true) -> true
// Do something.
}
Numbers
In php there are two data types for numeric data which are float and integer and both are defined as follows.
$age = 26; // Integer
$price = 12.5; // Float
There are several numerical operators you can use with numbers as follows.
$v = 2;
$x = 10;
$y = 12;
// Addition operator — Sum up values
$z = $x + $y; // 10 + 12 = 22
// Subtraction operator - Difference between values
$z = $x - $y; // 10 - 12 = -2
// Multiplication operator - Multiply values
$z = $x * $y; // 10 * 12 = 120
// Division operator - Divide values
$z = $y / $x; // 12 / 10 = 1.2
// Modulus operator - Get remainder after division
$z = $y % $x; // 12 % 10 = 2
// Exponentiation operator - Raise into a power
$z = $x ** $v; // 10 ** 2 = 100
There are some other operators, which can be used with numbers are discussed in the latter part.
Strings
Strings are covered using either double quotes or single quotes. There are slight differences between those. One is you cannot interpolate variables into a string if you wrap up with single quotes.
$name = "Yashod";
echo "Hello $name"; // Hello Yashod
echo 'Hello $name'; // Hello $name
In php string concatenation is done using “.” operator.
$firstName = "Yashod";
$lastName = "Perera";
echo $firstName . $lastName; // YashodPerera
echo $firstName . " " . $lastName; // Yashod Perera
In string characters can be retrieve using indexes.
$firstName = "Yashod";
echo $firstName[0]; // Y
There are lots of inbuilt functions in php and following are some for strings.
$firstName = "Yashod";
strlen($firstName); // 6 (Length of the string)
strtoupper($firstName); // YASHOD
strtolower($firstName); // yashod
Apart from above there are lots of inbuilt functions.
Arrays
There are three types of arrays in php naming,
- Indexed arrays
- Associative arrays
- Multidimensional arrays
Indexed arrays
These are arrays with numerical indexes as follows. In php you can include any data type in an array.
There are two ways of initialising an array.
$names = ["Peter", "Smith", "Mike"];
$names = array("Peter", "Smith", "Mike");
Printing array Values.
print_r($names);
Append new item or change existing values.
$names = ["Peter", "Smith", "Mike"];
// Append
$names[] = "Yashod";
array_push($names, "Yashod");
// Change values
$names[0] = "Dinuk";
Get number of elements in an array.
$names = ["Peter", "Smith", "Mike"];
count($names); // 3
There are so many inbuilt array function in php which you can refer from here.
Associative arrays
These arrays store data using key value pair as follows.
$array_name = [key => value, key => value];
$person = ["name" => "yashod", "age" => 24];
Then those values can be retrieved using those keys as follows.
echo $person["name"]; // yashod
Values can be added or change as follows.
$person["school"] = "Maris stella collage"; // Add
$person["age"] = 25; // Change
I am not going to talk about multidimensional arrays which have arrays inside an array.
Quick Tip: If you need to find the data type of a variable use gettype($var)
function.
Operators
Logical operators and arithmetic operators are discussed and in this section let’s discuss about assignment, comparison and increment/decrement operators.
Assignment Operators
These operators are used to assign a value to a variable. Note that if some value is added(any operation) to a particular value as follows we can use shortened operators.
$x += $y; // $x = $x + $y
Then following are some examples.
// Assign a single value.
$x = 10;
$y = $x; // $y = 10;// Addition
$y += $x // $y = $y + $x// Subtraction
$y -= $x // $y = $y - $x// Multiplication
$y *= $x // $y = $y * $x// Division
$y /= $x // $y = $y / $x// Modulus
$y %= $x // $y = $y % $x
Increment / Decrement Operators
This is used to add one to the value and there are two type for each which are pre increment/decrement and post increment/decrement
- Pre increment/decrement — Values are increment/decrement before it returns
$x = 10;
echo "++$x"; // 11
$y = 10;
echo "--$y"; // 9
- Post increment/decrement — Values are increment/decrement after it returns
$x = 10;
echo "$x++"; // 10
echo "$x"; // 11
$y = 10;
echo "$y--"; // 10
echo "$y"; // 9
Comparison Operators
These operators compare two values and output whether the condition is true or false.
if($x == $y){ // Check whether $x and $y equals.
}
if($x != $y){ // Check whether $x and $y not equals.
}
if($x == $y){ // Check whether $x and $y equals
}
if($x > $y){ // Check whether $x is greater than $y.
}
if($x < $y){ // Check whether $x is lesser than $y.
}
if($x >= $y){ // Check whether $x is greater or equal $y
}
if($x <= $y){ // Check whether $x is lesser or equal $y
}
Important : “==” wont check the type for that you have to use “===”.
if(10 == "10"){ // This becomes true.
}
if(10 === "10"){ // This becomes false.
}
Conditional Statements
In Programming you have to things according to conditions. As an example if price is above hundred calculate the total with the 10% discount and if it is less then the discount is 5%.
There are several types of conditional statements which are,
- if statement — There are three types of if statements as follows as if et checks one condition or more.
if(condition){
// Do something
}if(condition){
//Do something
} else {
// Do else
}if(condition){
// something
} elseif(condition){
// something
} else {
//something
}
- switch statement — This is used to check the exact values as follows.
$day = "monday"
switch ($day) {
case "Monday":
echo "Today is Monday";
break;
case "Tuesday":
echo "Today is Tuesday";
break;
case "Wednesday":
echo "Today is Wednesday";
break;
case "Thursday":
echo "Today is Thursday";
break;
case "Friday":
echo "Today is Friday";
break;
default:
echo "This is the weekend";
}
Important : If break is not mentioned it will execute the following case values.
- Ternary operator — Shortened if else statement.
if ($x == $y) {
echo "$x, $y are equal";
} else {
echo "$x, $y are not equal";
}
Above statement can be shortened using ternary operation as follows.
$x == $y ? echo "$x, $y are equal": echo "$x, $y are not equal";
Loops
Loops are used to execute a repetitive task for number of times. There are 4 types of loops as follows.
- For loops — Which get the initial value, condition and the increment as follows and it will executes the loop until the condition satisfies and it will increment the value according to the increment value in each iteration.
for(<initialize_counter>,<condition>,<increment>){
// Do something.
}
Following is an example.
for($i = 0, $i <5, $i++) {
echo "$i ";
}
Output : 0 1 2 3 4
- Extended for loop — This is also called as foreach loop which is used to iterate the values in an array as follows. It only take the array name.
foreach(<array_name> as <variable>){
// Do something.
}
Following is an example.
$names = ["yashod", "smith", "shawn"];
foreach($names as $name) {
echo "$name ";
}
output : yashod smith shawn
- while loop — This will loop until mentioned condition is false and the initialisation of the counter is done outside of the while loop.
<initialize_counter>
while(<condition>){
// Do something.
<increment>
}
Following is an example.
$i = 0;
while($i<5){
echo "$i ";
$i++;
}
output : 0 1 2 3 4
- do-while loop — This is similar as while loop but the difference is it execute the code once and then check according to the condition.
do{
// Do something;
} while (<condition>);
In loops we have to talk about two important key words which are break and continue.
- break — This will break the loop and exits.
for($i = 0; i < 5; i++){
if ($i == 3) {
break;
}
echo "$i ";
}
output : 0 1 2
— When it reaches to the 3 it will exit the loop because of the break statement.
- continue — This will the omit the below code in the block and jump to the next iteration.
for($i = 0; i < 5; i++){
if ($i == 3) {
continue;
}
echo "$i ";
}
output: 0 1 2 4
— This will omit the 3 because it executes the continue statement once reaches the 3.
Functions
Let’s do the final part of this which is functions. Functions are small piece of code which do a specific task.
- Functions get parameters (optional)
- Functions return a value (optional)
function functionName($parameters){
// Action
return <value>;
}
Example :
function add($value1 ,$value2){
$total = $value1 + $value2;
return $total;
}
Above function will get two values and output a single added value.
echo "add(2,3)"; // 5
In function we can mentioned some default parameters. It will take the default value if user doesn’t input the parameter as follows.
function hello($name=="Peter"){
echo "Hello $name";
}hello(); // Hello Peter
hello("Yashod"); // Hello Yashod
Hopefully this will cover all the fundamentals of PHP and there are lot more to learn. You can start code using these fundamental knowledge. In the next post let’s learn how to make a dynamic website using php and mysql.
If you have found this helpful please hit that 👏 and share it on social media :)