PHP, WordPress, Flutter and Dart

Mix and match the programming languages and Frameworks for a combination that will perhaps help me to share my learning experiences with the open source community.

Keeping that paradigm in my mind, I have changed the look of https://sanjibsinha.com

To sum up, we should learn programming languages that we can pick and choose for a good mixture.

Think of WordPress. A blend of HTML, PHP, CSS and JavaScript.

On the other hand Flutter is a mingling of Dart, HTML, Swift and Others.

I try to write regularly on these four topics in https://sanjibsinha.com, and you will find the code snippets at GitHub repository.

What is Algorithm?

discrete-mathematical-algorithm-data-structures
discrete-mathematical-algorithm-data-structures

https://leanpub.com/discretemathematicalalgorithmanddatastructures

Algorithm is expressed as a set of steps. By describing the actions at each step we instruct the computer do something. Usually we can use any natural language to describe the actions to perform at each step.

Consider this simple description.

  • 1. Enter one integer
    2. Enter another integer
    3. Compare both integers and return the maximum value
    4. Compare both integers and return the minimum value

In C++ programming language, on one hand, we can create generic functions to find the maximum or minimum value; and, on the other, we can take help from the ‘algorithm’ template library to find the same values.

Every high level language comes with its own algorithm library. They do so for one reason. Any system of counting or calculation by means of a device like computer involves following a steps or directions. Computer scientists use the word ‘algorithm’ to describe such as ‘set of directions’.

In some cases, these directions could be simple as described above. In most cases, it is much more complex. For complex cases, we need the help of ‘algorithm’ library. Otherwise, we have to do the low-level plumbing, which is much more time consuming and that takes us away from building other important parts of any application.

Historically, the derivation of this word has some interesting facts. At the beginning of ninth century an Arabian mathematician wrote a book called ‘Kitab al jabr w’al muqabala’ (Rules of Restoration and Reduction). The word ‘algebra’ comes from the title of the book. This textbook introduced the use of Hindu numerals and included a systematic discussion of fundamental operations on integers.

The word ‘algorithm’ comes from the name of the mathematician, Abu Ja’far Mohammed ibn Musa al-Khowarizmi.

One of the most famous and well known algorithms is of course Euclid’s Algorithm. It is a process for calculating the greatest common divisor (GCD) of two integers.
We can illustrate this algorithm in the following way.

  • 1. Take two integers x and y
    2. Divide y by x and get the remainder as r
    3. Now replace the value of x with the value of r and replace the value of y with the value of x
    4. Again divide y by x
    5. This process will continue until we get r = 0
    6. Once we get r = 0, stop the calculation, x is the GCD

Notice that the algorithm is expressed as a set of steps. Each step describes some action to take. The important thing is to describe the actions to be performed clearly and unambiguously.

Let us summarize this introductory part on algorithm in one sentence.
Data go inside the computer as inputs, algorithm takes charge, processing the data and after that the data as outputs come out.

By the way, people often mistake the word ‘data’ as singular; but, it is actually a plural form of the Latin word ‘datum’. Since we have used this word too often in our discourse, and will use in future, therefore, for the curious readers I opened up the Oxford dictionary and searched for the word: datum.

Oxford dictionary defines datum as “A thing given or granted; a thing known or assumed as a fact, and made the basis of reasoning or calculation; a fixed starting-point for a series of measurements etc.” It has also made it clear that the plural form of ‘datum’ is ‘data’.

For instance, in Java we have Collection class and in C++ we have containers that manage this data structure part. We are going to find out how they are related in the next post.

Why Laravel 5.7.* Model Relations are important to understand

laravel5-7allmodelsrelationsexplained

Laravel 5.7.* All Model Relations Explained

Any awesome Laravel application greatly depends on Model relations. How they work, what are the magical methods behind them? Explained lucidly with examples.

You will learn all Model relations and how you can use them to build a complicated web application.

Apparently, this contents management application does not look very complicated, however, the relations are quite tangled and we will try to understand these relations through Laravel’s Model relations and Eloquent ORM; at the end, we will also learn how resourceful controllers play vital roles in such model relations.

How an article is related to a particular user and how from the article table we can fetch the data of that particular user or writer? An article uses many tags, but how we can access those tags from that article itself? An article may have many comments. Who has written those comments? Of course users. And these users have their own profiles which tell us about them, including name, email, city, and a short biography. Each profile page may have multiple comments written by other users about that profile-holder user. So we have comments table for both – articles and profiles. Can we use one single comment table to serve them both? Yes, we can do! A polymorphic relationship allows us to do that.

These questions are all very tricky, however, laravel model relations, Eloquent ORM, and resourceful controllers has solved these problems quite easily. As we progress we will learn one-to-one, one-to-many, many-to-many, has-many-through, and polymorphic relationships with concrete examples. By the way, we will also learn some major tricks of Laravel (like resource controller and views) that makes your development experience more pleasant.

Finally, what we will see in this application? A user have many articles. When you open the application, you will find the series of article titles. Each title will show who is the writer of it. If you click on each title, you can read the full article. If you click on the user name, you will see the user’s profile and all the articles he/she has written. The same rule is applied for the tags. Each tag may belong to many articles. Again any article may belong to many tags. So each article shows many tags. In the user profile we will see which tags he/she has used often and so on. In addition to that, we have comments on both pages, with a link to the users who have written them.

All together, it’s an interconnected contents management application that handles many complex queries effortlessly.

Laravel, Ubuntu and PHP 7.2

Sometimes this task seems daunting; you have Ubuntu 16 as your default OS and each time while installing Laravel 5.*.*, you are left with error messages reminding you that you don’t have many PHP extensions in your system; PHP extensions that support Laravel.
What you can do?
It’s a problem and must have a solution.
Here is the solution.
You need to make your system Laravel friendly. That is the first step when you have to purge old PHP from your system and install the latest ones.

Continue reading Laravel, Ubuntu and PHP 7.2

How Composer has Revolutionized the PHP World

If you plan to design object-oriented software, it is hard, and, designing reusable object-oriented software is even harder. How can a dependency management system like Composer make this task easier? Let us try to understand that in this chapter. We will see more usages of Composer, as we read in the next chapters.
Composer’s role in Effective Patterns

I would like to start this section by quoting from the famous book “Design Patterns, Elements of Reusable Object-Oriented Software” by the “Gang of Four” Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.

Continue reading How Composer has Revolutionized the PHP World

MySQL or NoSQL

object-oriented-design-patterns-in-php7 for web
object-oriented-design-patterns-in-php7 for web

Edgar F Codd had invented it. Later it became exceptionally popular. The relational database management system (RDBMS) is a database management system based on the relational model. Today most databases use it.
MySQL is one of them. Along with PHP, we need to know about MySQL for one reason. MySQL is a central component of the LAMP open-source web application software stack. The LAMP is an acronym for “Linux, Apache, MySQL and Perl/PHP/Python”.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books. You can buy from either Leanpub or Amazon or from my publisher Apress.

How important MySQL is? Well, it really needs no introduction. Many popular applications, such as WordPress, Drupal or Joomla use it. Many high scale websites including Google, Facebook, Twitter, Flickr and YouTube draw on it.
Since the 1980s it has been a common practice for storage of information in databases used for different types of applications. From financial records to personal data – it’s much easier to implement and administer. RDBMS like MySQL maintain a clearer division between the database model and the application. RDBMS as MySQL received challenges, mainly, from two sectors – one is Object Database Management Systems ODBMS or OODBMS and the second one is XML database management system. However, they were unsuccessful.
As time passes by and the horizontal scaling of the computer clusters become popular, NoSQL is one of the most serious challenges RDBMS faces now.
Relational databases use tabular relations. The NoSQL databases use a data structure that consists of key-value, wide column graph or document. It is not only different from RDMS, but sometimes it is also faster. Sometimes people view it as more flexible.

File in PHP Example

object-oriented-design-patterns-in-php7 for web
object-oriented-design-patterns-in-php7 for web

There are several methods available for file opening, reading and writing.
Let’s check them one by one.
The first example deals with while() loop and feof() function. It returns true when you are at the end of the file. The code is like this:

/* 
 * Opening, reading and closing a file
 */
$handle = fopen("file.txt", "r");
while (!feof($handle)) {
    $text = fgets($handle);
    echo $text ;    
}
fclose($handle);

At the end of the file, while() loop returns true, and you can read the entire file.
When you’re done with the file reading, don’t forget to close the file by fclose() function. It frees up the resource so that if you want to work with the same handle later, it avoids any other conflict.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books. You can buy from either Leanpub or Amazon or from my publisher Apress.

As always we can also read a file by character with fgetc() function.

/* 
 * Opening, reading by character and closing a file
 */
$handle = fopen("file.txt", "r");

while ($char = fgetc($handle)) {    
    if($char == "\n"){
        $char = ; // use the br tag for n
    }
    echo $char";    
}
fclose($handle);

Here you start by opening the file to read from, file.txt. Next, we loop over all the characters.
You can read a file just like an array. Each line acts like a $key. And the $value denotes the line. You can also var_dump() the whole file and see what is inside.

/* 
 * reading a file into an array
 * each line is a new value
 */

$data = file("file.txt");
//var_dump($data);
foreach ($data as $key => $value) {
    echo $key . " = " . $value;
}

In the above code, we’ve used the file() function. This file() function can get the file data in array type, so that you can loop over it, and read the lines one by one.
Uploading a file is also easy.

This type of form is special. We need to mention the type, method and the action-destination in the first line.
And then in the “file-process.php” file we catch the file data as an array.


/* 
 * to get the file data
 */

/*
$handle = fopen($_FILES['userfile'] ['tmp_name'], "r");

while (!feof($handle)) {
    $file = fgets($handle);
    echo $file;
}
fclose($handle);
*/

$handle = file_get_contents($_FILES['userfile'] ['tmp_name'], "r");

$full_text = str_replace("\n", "br", $handle);

echo $full_text;

We can catch them either way. By using the while loop, which is commented out here. Or we can catch the file data by superglobal array $_FILE[‘input-name’] using file_get_contents() function.
Reading files in one go, is always important.
There are functions that might come to our help.

/* 
 * reading a whole file at once
 * 
 */
$handle = file_get_contents("file.txt");
$full_text = str_replace("\n" , "br", $handle);
echo $full_text;

In the above code we get the contents of the file “file.txt” in one go. And after that, we have used str_replace() php-built-in function to format it properly; so that line breaks and we can read the file in our web page.
Suppose, you want to work with a file, that doesn’t exist at all. In such cases, an unnecessary error page will show up. We don’t want this in our production server.
To prevent this, you need to check if a file exists with the file_exists() function.
If a file doesn’t exist, you can display a message to that effect. It is better than an ugly error page!


$filename = "file.txt";
if (file_exists($filename)){
    $data = file($filename);
    foreach ($data as $key => $value) {
        echo "Line number : {$key} : " . $value;
        echo "The file size is " . filesize($filename) . " bytes long.";
    }
}
else{
    throw new Exception($filename . " does not exist");
}

You can run the code and see the result yourself.
So far you have seen that the files have been handled as text files. You can handle them in a binary way as well using a function like fread().
But there is one thing, that you have to understand. When you are going to read a file binary way, you need to determine the file-size also.
You can always know the file size of any file by filesize() function. And at the same time you can use this function to read any file binary way.


$handle = fopen($filename, "rb");
$text = fread($handle, filesize($filename));
$full_text = str_replace("\n", "br", $text);
echo $full_text;
fclose($handle);

Remember, the mode is “rb”, that is read binary.
The file handling power of php is limitless. You can do so many things with simple commands.
Suppose you have a list of names in a text file. You can read the first-name and second-name in an array type or any format that suits you.
The function fscanf($handle, string $format); comes handy when you want to format a string of same type. If the names are separated by tabs, you can easily get the output by this function.


$handle1 = fopen($filename, "r");
while ($file = fscanf($handle1, "%s\t%s\n")) {
    list($word1, $word2) = $file;    
    echo $word1, " ", $word2;
}
fclose($handle1);

Parsing file is also important when you want to parse ‘ini’ files. The ‘ini’ files refer to the initialization files that Windows OS and other operating systems require. Installing php also comes with a ‘php.ini’ file. Don’t try to parse it this way.
Also remember, there are lots of reserved keywords for php. You cannot use them as keys for ‘ini’ files.
We use parse_ini_file() function to get the contents in an associative array. If you set the ‘process_sections’ parameter true, you get a multidimensional array.
We’ll again come to the ‘parsing section’, but before that knowing file information is important.
Getting file information becomes easier with the stat( $filename ) function.
Consider this code before proceeding further.


$filename = "file.txt";
$array = stat($filename);
echo "The file device number is :" . $array['dev'];
echo "The file Inode number is :" . $array['ino'] ";
echo "The file userID of owner is :" . $array['uid'];
echo "The file group ID of owner is :" . $array['gid'];
echo "The file size is :" . $array['size'];
echo "The file time of last access is :" . $array['atime'];
echo "The file time of last modification is :" . $array['mtime'];

Using stat() function we have got an array of values. We have used array[$key] to get the value. Let’s clarify one after another. $array[‘dev’] stands for device name. The second one $array[‘ino’] is Inode number. You could have also known Inode protection mode by using $array[‘mode’].
The ‘uid’ and ‘gid’ is user ID and group ID of the owner. Now, it makes sense for the Unix machines. You can get the file-size by ‘size’ key. You can also know the time of last access and last modification by ‘atime’ and ‘mtime’.
Now let’s come to the parsing ‘ini’ file again. Before parsing the file we need to create an ‘ini’ file. Suppose it is ‘sample.ini’ file.

; last modified 1 April 2018 by Sanjib Sinha
[owner]
name=Sanjib Sinha
LastLocated=Las Vegas.

[book]
; use git to get code
file="/usr/local/bin/book.code"
URL="http://www.sanjibsinha.com"

Here we have started with a comment. Next part – ‘book’ and ‘owner’ are the sections.


echo '
How to parse .ini file';

$filename = "sample.ini";
$array = parse_ini_file($filename);
foreach ($array as $key => $value) {
    echo "
 {$key} = {$value}";
}

And here is the output.

name = Sanjib Sinha 
 LastLocated = Las Vegas. 
 file = /usr/local/bin/book.code 
 URL = http://www.sanjibsinha.com 
The output recovers the values as we have gone through a loop and read the array key one by one. The keys and values are displayed one after another.
You can also delete this ‘sample.ini’ file or any file by a simple function unlink( $filename ). Using if-else logic, you can get a nice output of your result. 
Copying any file is extremely easy. The function copy($filename, $dest, $context); means you need a source file. The second parameter stands for the destination file. The third parameter is optional. If you want to copy any file to a URL, the copy operation may fail. It depends on one thing. If the wrapper does not support overwriting the existing file, it will fail. If it allows, then the existing file is overwritten. 
In our code, we copy a file to a local folder.
$filename = "file.txt";
$copy = "copy.txt";

if(copy($filename, $copy)){
    echo 'Copied ' . $filename;
}
else{
    echo 'Could not copy ' . $filename;
}

We copy ‘file.txt’ and the new file is automatically saved as ‘copy.txt’.
So far we have seen many functions that involve mainly file reading. File writing in php is also super easy. You need to set up your system before you want to write files. In Windows you can right-click the folder and click the Web-Sharing tab. In Linux based system you can open the terminal and type this command:

sudo chmod +w file.txt 

You can even make it executable by issuing this command:

sudo chmod 777 file.txt 

Classes in php

 

object-oriented-design-patterns-in-php7 for web
object-oriented-design-patterns-in-php7 for web

PHP 7 has a full object model and now we consider it as fully object oriented programming (OOP) language.
For a small website, where four, five pages represent a simple profile, you don’t need OOP. Object Oriented Programming is targeted at larger applications. In addition, I hope, one day, you’ll definitely build a large web application with other team members. For that purpose and to master PHP, you need to learn and adapt to OOP style.
For that reason, OOP was created – to break up large applications when long function did not work.
In the beginning, programming started in a linear fashion. Programmers wrote code, line after line. It took time to debug. Then came the concept of functions. We started encapsulating our data into a function.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books. You can buy from either Leanpub or Amazon or from my publisher Apress.

However, it had limitations. It broke up the code but the code would not run until called.
As time passed by, we had badly needed a change. Web applications started becoming larger in volume. The solution was to use objects. To start a car you need to start the engine, accelerate, use break and steering, and switch on AC, and so on. Lot of functions to be written. Lot of variables to be declared and assigned. How about wrap them all into a single conceptualized object – a car.
Now all the internal workings are hidden and as a car owner or a driver, you do not want to know how the internal workings play their roles. You know your car moves. It stops. It honks. You are happy.
4.1.1 Classes
When we describe someone as good, we actually refer to a “type”.
Classes are the type of objects. Like integer is a type of a variable. This conception is particularly important. A class is a type of an object and many things depend on that. The main purpose of object is to create a class first. Without a car class, you cannot create a car object.
If class is the type of an object, then the object is the instance of a class.
Let’s see an example first.


                
                // let us create a house building App
                // we need to create a type 
                // and we want to create different types of house objects
                
                class House {
                    
                    // each house has doors
                    // they could have different colors

                    public $door;

                    function __construct($door) {
                        
                        $this->door = $door;
                    }

                }
                
                $house1 = new House("Red");
                
                echo "We have just created a house with " . $house1->door . " door.";
                
                $house2 = new House("Blue");
                
                echo "We have just created a house with " . $house2->door . " door.";

Now we would like to see the similar output in the old procedural style. Consider this code:


                
                // let us assume we want to create the same functionality 
                // procedurally
                //$door = "RED";
                
                function House1($door) {
                    
                    //global $door;
                    $door = "Red";
                     echo "We have just created a house with " . $door . " door.";
                     
                }
                function House2($door) {
                    
                    //global $door;
                    $door = "Blue";
                     echo "We have just created a house with " . $door . " door.";
                     
                }
                
                House1("Red");
                House2("Blue");
                
                // for different houses we need to create different functions
                // no reusability
                // no separation of codes

The main problem is – for different houses, you need to create different functions. The whole process becomes cumbersome.
In the first scenario, we created one type of the house object. It was “class House”. In that type, we mentioned the “door” property so that each new house might have different colors. We did not have to write separate functions for each house. One class. One type. In addition, that was enough to create many houses.
Consider another example where in a “buying app” we set a minimum price. No one can buy a product paying less than 2 dollar.



                
                // imagine a buying app
               // where we set a price ranging between two values
                // 2 to 10 dollars
                
                class BuyMe {
                    
                    public $product;
                    
                    public $price;

                    function __construct($product) {
                        
                        $this->product = $product;
                    }
                    
                    public function setPrice($price) {
                        
                            $this->price = $price;
                            $minimumPrice = 2;
                            if($this->price price;}
                            
                    }
                    
                    public function getPrice() {
                        
                        return $this->price;
                        
                    }

                }
                
                $mobile = new BuyMe("Mobile");
                
                $mobile->setPrice(10);
                
                echo $mobile->getPrice();

We need to clarify a few things.
First, to create a class, we need a class keyword. Next, it is not mandatory that we should always write the __construct() method. Although, whenever an object is instantiated, this constructor method is called first. If you want to pass any data in the beginning, you can pass through it.
In the second example, we have used set() and get() methods. These setter and getter methods are extremely handy when we need some validation. Here the price is set so you get the price. If it were not, it would throw an exception.
Nothing is mandatory here. If you don’t want, just don’t write it.

Types of flow control in PHP

wp1//embedr.flickr.com/assets/client-code.js
Flow control is the point where you start making decisions in your code. Next, you execute further code depending on those decisions.
In human language, “if” is a conjunction. Here, in programming, it is a statement.

If(expression){
statement
}

Here, expression is a php expression that evaluates TRUE or FALSE value. If your expression is TRUE, the statement that follows is executed. If it’s FALSE, it’s not executed.
Before moving forward, I’d suggest you to consult any beginner’s PHP book where you can learn about operators – conditional and logical, both. You also need to know about operator precedence.
Let us see one quick example.

//if there is two possibilities
$low = 10;
$high = 30;
$temp = 20;

if ($temp $high){
echo 'Stay inside';
}
else{
echo 'Nice temperature out.';
}

Here we have checked the temperature outside. We have assigned a value (20) to the $temp variable. It is neither lower than the low temperature (10) nor it is higher than the high temperature (30). So our output is obvious. The php expression is FALSE. So the output will be “Nice temperature out.”
Now, we can also write the same code in a different way. It is called ‘Ternary Operator’. This is a built-in operator that acts like an if statement. However, it has an unusual form.

object-oriented-design-patterns-in-php7 for web
object-oriented-design-patterns-in-php7 for web


Here is the example where we are trying to test the same code through ternary operator. I give the full code, so that you can compare it with the if statement.


//if there are two possibilities
$low = 10;
$high = 30;
$temp = 20;

if ($temp $high){
echo 'Stay inside';
}
else{
echo 'Nice temperature out.';
}

echo '
';

//we can also write it using ternary operator
$ter = ($temp $high) ? "Stay in" : "Go out";
echo $ter;

In the ternary operator, we put the expression part within first bracket. After that, we have used a question mark. We keep two possibilities. In addition, to differentiate two possibilities we put a colon between them.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books.
You can buy from either Leanpub or
Amazon or from my publisher Apress.

Now, consider a third possibility. To solve that problem, we introduce “elseif” between “if and else”.

if ($temp > $high)
{
echo "Don’t go out.";
}
elseif ($temp < $low)
{
echo " Don’t go out.";
}
else
{
echo " It is good outside.";
}

You can continue using “elseif” as long as you wish. You can test many possibilities.
To test many possibilities, you can use “switch” statement.


// Example of switch statement

$variable = 45;

switch ($variable) {
case 5:
case 10:
case 14:
echo 'Too cold.';
break;
case 15:
case 20:
case 22:
echo 'Moderate.';
break;
case 30:
case 35:
case 40:
echo 'Too hot.';
break;

default:
echo 'If all cases fail, this will be the final value: it is not good out.';
break;
}

Here a temperature is given and we test that temperature against many possibilities. We can write as many “cases” as possible, it is just like “elseif”.
Now comes the best part of flow control.
Loop.
You know that computers are great at doing repetitive tasks. Moreover, we are happy knowing that, because we don’t like doing repetitive tasks. That makes computer strong and popular. Like other programming languages, php also comes with standard loops that help computer doing the repetitive tasks easily.
Here is an example of “for loop”.

//$index = 1;

for ($index = 0; $index < 3; $index++) {

if ($index == 0){continue;}
echo "1/$index : " . 1/$index . "
";
//$index++;

}

While loop statement is slightly different in nature and you should handle it carefully. As a beginner, one may make a mess in the code if he or she cannot write while loop properly.
It is very good in calculating few typical applications like gross salaries of 200 different persons. Or you may want to take a list of highest and lowest temperatures of a definite month or a year.
Although the while statement is simple, people may make mistake. It happens because while loop executes the statement repeatedly as long as the condition is true.

$num=1;
while ($num <=10)
{
echo "Increment Number : $num
";>
$num = $num + 1;
}

Forgetfully if you wrote the opposite way, that is, if you wanted to check whether $num is greater than 10, suddenly there would be a lot of confusion. The infinite loop traps the code in such cases and it continues until the end.
On the other hand, foreach loop statement works only on arrays. It is easy to handle. For manipulating and working on array, it is extremely essential.
We write it in this way:
foreach ($array as $key => $value) {

}
Suppose we want to find total numbers of a given array. The code will be like this:
$array = [10, 25, 123654, 7854];
foreach ($array as $value) {

//the total of the numbers
$TotalOfTheNumbers = $TotalOfTheNumbers + $value;

}
Sometimes, you can ignore the key for the numbers as the key starts from 0. In the above code, the values are important.

php functions example

test1//embedr.flickr.com/assets/client-code.js

Creating your own functions in PHP is our next big step in web programming. You’ve already seen a few built-in PHP functions already.
What are functions? The functions are the callable sections of your code where you can pass data and it returns data to you. Do you have some parts of code to run multiple times in your code? Put them into a function. Got some code that shouldn’t run automatically when the page loads? Put it into a function. Is there a too long code that is difficult to debug? Break it into several functions so that you can pinpoint the error easily.
Now, let’s try to understand it from a different point of view.

object-oriented-design-patterns-in-php7 for web
object-oriented-design-patterns-in-php7 for web

In any language, “Noun, Adjective, Adverb, Pronoun, Articles” do not do anything. They definitely take part in the action. But without the verb an action remains incomplete. Functions in PHP play the same role. This is the action part. You pass some data and the functions return you some data. Try to imagine a simple function where you pass two integers and the function adds it and gives you back the result.
I hope it helps.
By putting code into a function, you actually convert it into action-verb. Such as, you’re putting some air in a function and when you call it, it generates electricity. Think this way; you pass ‘air’ data into a function and it returns ‘electricity’ data.
So we learn a very important thing. If I pass data to a function, it returns data. You’ll find this concept in every programming language. But PHP has some unique features.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books.
You can buy from either Leanpub or
Amazon or from my publisher
Apress.

Remember, it’s just the beginning of an interesting journey. You are going to learn how to divide up your code. Learning functions is the precursor to the next big thing – object oriented programming (OOP). In the next chapter we’ll learn how OOP lets you wrap both functions and data into classes and objects, so that the coding becomes easier.

BASIC FUNCTIONS WHERE WE PASS SOME DATA

How do you build your own function?
It’s very easy. The structure is like this:
function function_name ([argument_list_to_pass_data]){
“””Some statements, works to be done”””
return Returning_data
}
If you’re complete new, this example really doesn’t make sense. So let’s see some real-world-examples. Imagine a situation, where a user visits your website. The user logs in, so that your website automatically knows that username and greets him or her.
You need to write several functions until you reach the end. But we can, at least, write a very simple function to understand the core conception. Suppose the user’s name is Sanjib.


function GreetingsDisplay($message, $username) {
    
    return $message . " " . $username;
    
}


echo GreetingsDisplay(“Hello”, “Sanjib”);
The function greets you with the message – Hello Sanjib.
People describe science as the greatest adventure in this world. I think learning php is no less. Let’s be more adventurous and build a little bit more complex application.
In this application, we pass an array of numbers through a function and get the average of that number.
Remember, if you don’t pass any number, it’ll give you an output like this – “No Input”.
Here is the example code:



                // suppose we have some numbers in array
                $numbers = [];
                
                echo averager($numbers);
                
                function averager($array) {
                    
                    $TotalOfTheNumbers = 0;
                    $average = 0;
                    $NumberOfNUmbers = 0;
                
                    foreach ($array as $value) {

                        //the total of the numbers
                        $TotalOfTheNumbers = $TotalOfTheNumbers + $value;

                    }
                    //how many numbers ar there
                    $NumberOfNUmbers = count($array);
                    
                    //if there is no input
                    
                    if(count($array) > 0){
                        
                        //we'll get some verage value
                        $average = $TotalOfTheNumbers/$NumberOfNUmbers;
                        return $average;
                        
                    }
                    else{
                        
                        echo 'No input';
                        
                    }  
                    
                } 
                

Functions are integral parts of your web application. The basic duty of a function is – it gets data inside and gives an output. This output may become inputs of another function; and your application grows.
PASSING BIG DATA THROUGH FUNCTIONS
Now the time has come to take the stage for the big moment.


                
                $num = 4;
                
                //we want to square the value in a variable
                //will that change the original value?
                //the answer is NO

                function squarer($number) {
                    
                    $number *= $number;
                    return $number;
                    
                }
                //before the function call
                echo "The original value - " . $num;
                
                squarer($num);
                
                //after the function call
                echo "After the function call, the original value remains same - " . $num;
                
                
                /*
                 * our conclusion:
                 * the function could not change the original value
                 * a copy of that value was passed and the original value remained unchanged
                 * But, if we pass the value by reference, the original value is also changed
                 */
                
                function passByRef(&$param) {
                    
                    $param *= $param;
                    return $param;
                    
                }
                
                passByRef($num);
                //after the new function call
                echo "After passing data by reference, the original value takes the new value - " . $num;

                

This function is a big deal. Why? It’s because, you have learned how to pass data by reference and thereby change the actual value.
We have declared a number and assign a value – 4 to it. Now, we have passed that number through a function that multiplies that number by itself making it 16. But the number has not changed. Why it happens? It happens, because, generally, when we pass any value through any function, a copy passes through it. Not the original one. The original one remains unchanged.
Now look at the second part of the above code.


function passByRef(&$param) {
                    
                    $param *= $param;
                    return $param;
                    
                }
                
                passByRef($num);
                //after the new function call
                echo "After passing data by reference, the original value takes the new value - " . $num;


This time we have passed the value by reference and the original value changes. The original value was 4. Now it is 16.