Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, May 8, 2020

Include and Require Keyword

Including a PHP File into Another PHP File: The include() and require() statement allows you to include the code contained in a PHP file within another PHP file. Including a file produces the same result as copying the script from the file specified and pasted into the location where it is called. 

You can save a lot of time and work through including files — Just store a block of code in a separate file and include it wherever you want using the include() and require() statements instead of typing the entire block of code multiple times. A typical example is including the header, footer and menu file within all the pages of a website.

The basic syntax of the include() and require() statement can be given with:

include("path/to/filename"); -Or- include "path/to/filename";
require("path/to/filename"); -Or- require "path/to/filename";

Note:  Like the print and echo statements, you can omit the parentheses while using the include and require statements as demonstrated above.

The following example will show you how to include the common header, footer and menu codes which are stored in separate 'header.php', 'footer.php' and 'menu.php' files respectively, within all the pages of your website. Using this technique you can update all pages of the website at once by making the changes to just one file, this saves a lot of repetitive work.

<!DOCTYPE html>

<html lang="en">

<head>

    <title>Tutorial Republic</title>

</head>

<body>

<?php include "header.php"?>

<?php include "menu.php"?>

    <h1>Welcome to Our Website!</h1>

    <p>Here you will find lots of useful information.</p>

<?php include "footer.php"?>

</body>

</html>


Difference Between include and require Statements

You might be thinking if we can include files using the include() statement then why we need require(). Typically the require() statement operates like include().

The only difference is — the include() statement will only generate a PHP warning but allow script execution to continue if the file to be included can't be found, whereas the require() statement will generate a fatal error and stops the script execution.

<?php require "my_variables.php"?>

<?php require "my_functions.php"?>

<!DOCTYPE html>

<html lang="en">

<head>

    <title><?php displayTitle($home_page); ?></title>

</head>

<body>

<?php include "header.php"?>

<?php include "menu.php"?>

    <h1>Welcome to Our Website!</h1>

    <p>Here you will find lots of useful information.</p>

<?php include "footer.php"?>

</body>

</html>

 

Note: It is recommended to use the require() statement if you're including the library files or files containing the functions and configuration variables that are essential for running your application, such as database configuration file.

The include_once and require_once Statements

If you accidentally include the same file (typically functions or classes files) more than one time within your code using the include or require statements, it may cause conflicts. To prevent this situation, PHP provides include_once and require_once statements. These statements behave in the same way as include and require statements with one exception.

The include_once and require_once statements will only include the file once even if asked to include it a second time i.e. if the specified file has already been included in a previous statement, the file is not included again. To better understand how it works, let's check out an example. Suppose we've a 'my_functions.php' file with the following code: 

<?php

function multiplySelf($var){

    $var *= $var// multiply variable by itself

    echo $var;

}

?>

Here's is the PHP script within which we've included the 'my_functions.php' file. 

<?php

// Including file

require "my_functions.php";

// Calling the function

multiplySelf(2); // Output: 4

echo "<br>";

 

// Including file once again

require "my_functions.php";

// Calling the function

multiplySelf(5); // Doesn't execute

?>

When you run the above script, you will see the error message something like this: "Fatal error: Cannot redeclare multiplySelf()". This occurs because the 'my_functions.php' included twice, this means the function multiplySelf() is defined twice, which caused PHP to stop script execution and generate fatal error. Now rewrite the above example with require_once.

<?php

// Including file

require_once "my_functions.php";

// Calling the function

multiplySelf(2); // Output: 4

echo "<br>";

 

// Including file once again

require_once "my_functions.php";

// Calling the function

multiplySelf(5); // Output: 25

?>

As you can see, by using require_once instead of require, the script works as we expected.


Thursday, May 7, 2020

PHP String Functions

In this section, we will discuss a few basic string functions which are most commonly used in PHP scripts.

1. Getting length of a String: PHP has a predefined function to get the length of a string. Strlen() displays the length of any string. It is more commonly used in validating input fields where the user is limited to enter a fixed length of characters.

<?php
echo strlen("Welcome to Cloudways");    //will return the length of given string
?>

Output

20

 

2. Counting of the number of words in a String: Another function that enables the display of the number of words in any specific string is str_word_count(). This function is also useful in the validation of input fields.

<?php
echo str_word_count("Welcome to Cloudways");
//will return the number of words in a string
?>
 

Output

3


3. Reversing a String: Strrev() is used for reversing a string. You can use this function to get the reverse version of any string.

<?php
echo strrev(“Welcome to Cloudways”);// will return the string starting from the end
?>

Output

syawduolC ot emocleW


4. Finding Text Within a String: Strpos() enables searching particular text within a string. It works simply by matching the specific text in a string. If found, then it returns the specific position. If not found at all, then it will return “False”. Strops() is most commonly used in validating input fields like email.

<?php
echo strpos(“Welcome to Cloudways”,”Cloudways”);
?>

Output

11

 

5. Replacing text within a string: Str_replace() is a built-in function, basically used for replacing specific text within a string.

<?php
echo str_replace(“cloudways”, “the programming world”, “Welcome to cloudways”);
?>

Output

Welcome to the programming world

 

6. Converting lowercase into Title Case: Ucwords() is used to convert first alphabet of every word into uppercase.

<?php
echo ucwords(“welcome to the php world”);
?>

Output

Welcome To The Php World

 

7. Converting a whole string into UPPERCASE: Strtoupper() is used to convert a whole string into uppercase.

<?php
echo strtoupper(“welcome to cloudways”);// It will convert all letters of string 
                                            into uppercase
?>

Output

WELCOME TO CLOUDWAYS

 

8. Converting whole String to lowercase: Strtolower() is used to convert a string into lowercase.

<?php
echo strtolower(“WELCOME TO CLOUDWAYS”);

?>

Output

welcome to cloudways

 

9. Repeating a String: PHP provides a built-in function for repeating a string a specific number of times.

<?php
echo str_repeat(“=”,13);

?>

Output

=============


10. Comparing Strings: You can compare two strings by using strcmp(). It returns output either greater than zero, less than zero or equal to zero. If string 1 is greater than string 2 then it returns greater than zero. If string 1 is less than string 2 then it returns less than zero. It returns zero, if the strings are equal.

<?php
echo strcmp(“Cloudways”,”CLOUDWAYS”);
echo “<br>”;
echo strcmp(“cloudways”,”cloudways”);//Both the strings are equal
echo “<br>”;
echo strcmp(“Cloudways”,”Hosting”);
echo “<br>”;
echo strcmp(“a”,”b”);//compares alphabetically
echo “<br>”;
echo strcmp(“abb baa”,”abb baa caa”);//compares both strings and returns the result 
                                        in terms of number of characters.
?>

Output

1

0

-1

-1

-4

 

11. Displaying part of String: Through substr() function you can display or extract a string from a particular position.

<?php
echo substr(“Welcome to Cloudways”,6).”<br>”;
echo substr(“Welcome to Cloudways”,0,10).”<br>”;
?>

Output

e to Cloudways

Welcome to

 

12. Removing white spaces from a String: Trim() is dedicated to remove white spaces and predefined characters from a both the sides of a string.

<?php
$str = “Wordpess Hosting”;
echo $str . “<br>”;
echo trim(“$str”,”Wording”);
?>

Output

Wordpess Hosting

pess Host


Functions in PHP

  • A function is a reusable piece or block of code that performs a specific action.
  • Functions can either return values when called or can simply perform an operation without returning any value.
  • In PHP, we can define Conditional function, Function within Function and  Recursive function also.
  • PHP has over 700 functions built in that perform different tasks.

Why use Functions?

  • Better code organization – functions allow us to group blocks of related code that perform a specific task together.
  • Reusability – once defined, a function can be called by a number of scripts in our PHP files. This saves us time of reinventing the wheel when we want to perform some routine tasks such as connecting to the database
  • Easy maintenance- updates to the system only need to be made in one place.

Built-in Functions

Built in functions are functions that exist in PHP installation package.

These built-in functions are what make PHP a very efficient and productive scripting language.

PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.

PHP User-Defined Functions

In addition to the built-in functions, PHP also allows you to define your own functions. It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately from the main program

The basic syntax of creating a custom function can be given with:

function functionName(){
    
// Code to be executed
}

The declaration of a user-defined function start with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}.

Let’s now create our first function. We will create a very basic function that illustrates the major components of a function in PHP.

<?php
//define a function that displays hello function
function add_numbers(){   
        echo 1 + 2;
}
add_numbers ();
?>

Output:

3

  HERE,

  • “function…(){…}”  is the function block that tells PHP that you are defining a custom function
  • “add_numbers” is the function name that will be called when using the function.
  • “()” can be used to pass parameters to the function.
  • “echo 'Hello function!';” is the function block of code that is executed. It could be any code other than the one used in the above example.

Functions with Parameters

Let’s now look at a fairly complex example that accepts a parameter and display a message just like the above function.

Suppose we want to write a function that prints the user name on the screen, we can write a custom function that accepts the user name and displays it on the screen.

The code below shows the implementation.

<?php
function display_name($name)
{
echo "Hello " . $name;
}
display_name("Martin Luther King");
?>

Output:

Hello Martin Luther King

  HERE,

“…($name){…” is the function parameter called name and is initialized to nameless. If no parameter is passed to the function, nameless will be displayed as the name. This comes in handy if not supplying any parameter to the function can result in unexpected errors.

Let’s now look at a function that accepts a parameter and then returns a value. We will create a function that converts kilometers to miles. The kilometers will be passed as a parameter. The function will return the miles equivalent to the passed kilometers. The code below shows the implementation.

<?php
function kilometers_to_miles($kilometers = 0)
{
$miles_scale = 0.62;
return $kilometers * $miles_scale;
}
echo kilometers_to_miles(100);
?>

Output:

62

Functions with Optional Parameters and Default Values

You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign, followed by a default value, like this.

<?php
// Defining function
function customFont($font, $size=1.5){
    echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}
// Calling function
customFont("Arial"2);
customFont("Times"3);
customFont("Courier");
?> 

As you can see the third call to customFont() doesn't include the second argument. This causes PHP engine to use the default value for the $size parameter which is 1.5.

Passing Arguments to a Function by Reference

In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However, to allow a function to modify its arguments, they must be passed by reference.

Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function definition, as shown in the example below:

<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
    $number *= $number;
    return $number;
$mynum = 5;
echo $mynum// Outputs: 5
 
selfMultiply($mynum);
echo $mynum// Outputs: 25
?>

Conditional Control Structures

Conditional statements are used to perform different actions for different conditions. In PHP we have the following conditional statements:

  • if statement – executes some code if one condition is true
  • if…else statement – executes some code if a condition is true and another code if that condition is false
  • if…elseif…else statement – executes different codes for more than two conditions
  • switch statement – selects one of many blocks of code to be executed

The if Statement

The if statement executes some code if one condition is true.

<?php
$t = date("H");
// if structure
if ($t < "15")
{
echo "Have a good day!";
}
?> 

The if…else Statement

The if…else statement executes some code if a condition is true and another code if that condition is false.

<?php
$t = date("H");
// if-else control Structuer
    if ($t < "15")
    {
    echo "Have a good day!";
    }
    else
    {
    echo "Have a good night!";
    }
?>

The if…elseif…else Statement

The if…elseif…else statement executes different codes for more than two conditions.

<?php
$t = date("H");
// if-esleif-else control structure
    if ($t < "15")
    {
    echo "Have a good morning!";
    }
    elseif ($t < "25")
    {
    echo "Have a good day!";
    }
    else
    {
    echo "Have a good night!";
    }
?>

The Switch Statement

The switch statement is used to perform different actions based on different conditions. It is used to select one of many blocks of code to be executed.

<?php
$favcolor = "blue";
// Switch control Structure
    switch ($favcolor)
    {
    case "blue":
    echo "Your favorite color is blue!";
    break;
    case "green":
    echo "Your favorite color is green!";
    break;
    case "black":
    echo "Your favorite color is black!";
    break;
    default:
    echo "Your favorite color is neither blue, green nor black!";
}

?> 

PHP Loops

When we write a code, we want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform the same task. In this PHP Tutorial we will learn about the three looping statements.

In PHP, we have the following looping statements:

  • while – loops through a block of code as long as the specified condition is true
  • do…while – loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for – loops through a block of code a specified number of times

The While Loop

The while loop executes a block of code as long as the specified condition is true.

<?php 
$a = 3;
// while iterative structure 
while($a <= 5)
{
echo "The number is: $a <br>";
$a++;
?> 

The do..while Loop

The do…while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

<?php 
$a = 3;
// do-while iterative structure
do
{
echo "The number is: $a <br>";
$a++;
}
while ($a <= 5);
?> 

The For Loop

PHP for loops execute a block of code a specified number of times. It is used when you know in advance how many times the script should run.

<?php 
// For loop 
for ($x = 0$x <= 10$x++)
{
echo "The number is: $x <br>";
?>

Now that you have learnt about the Conditional Statements and Loops in PHP, let’s move ahead with the PHP Tutorial and learn about the Functions in PHP.

foreach Loop

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value)
{
code to be executed;
}

example of foreach loop

<?php
$fruits = array("mango""apple""papaya""lichi");
// foreach loop structure
foreach ($fruits as $value)
{
echo "$value \n";
}
?>


 



Data-types, Variables and Operators

PHP Data types

A variable can store different types of Data. Let’s have a look at some of the data types supported by PHP:


PHP String

A string is a sequence of characters. In PHP, you can write the string inside single or double quotes.

<?php $a = "Hello World!";
$b = 'Hello World!';
echo $a;
echo "<br>";
echo $b
?>

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. An integer must have at least one digit and can be either positive or negative.
The following example takes $a as an integer. The PHP var_dump() function returns the data type and value.

<?php 
$a = 0711;
var_dump($a); 
?> 

PHP Float

A float or floating point number is a number with a decimal point or a number in exponential form.

The following example takes $a as a float and the PHP var_dump() function returns the data type and value.

<?php
$a = 14.763;
var_dump($a);
?> 

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE. They are often used in conditional testing.

$a = true;
$b = false;

PHP Object

An object is a data type which stores data and information on how to process that data. In PHP, an object must be explicitly declared. We need to declare a class of object using the class keyword.

<?php
class Student
{
    function Student()
    {
    $this->name = “XYZ”;
    }
}
// create an object
$Daniel = new Student(); // show object properties
echo $Daniel->name
?>

PHP Array

An array stores multiple values in one single variable. In the following example, the PHP var_dump() function returns the data type and value.

<?php 
$students = array(“Daniel”,”Josh”,”Sam”);
var_dump($students); 
?>

Now that you have learnt about the various Data Types, let’s move ahead with the PHP Tutorial and have a look at the different PHP Variables. 

PHP Variables

Variables are containers for storing information. All variables in PHP are denoted with a leading dollar sign ($). Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Declaring PHP Variables:

<?php
$txt = "Hello World!";
$a = 7;
$b = 11.5
?>

The PHP echo statement is often used to output data to the screen.

PHP Variables Scope

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be used.

In PHP we have three different variable scopes:

            1. Local – A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

<?php 
    function myTest() 
    { 
    $a = 7// local scope 
    echo "<p>Variable a inside function is: $a</p>"
    } 
    myTest(); // using x outside the function will generate an error echo 

"<p>Variable a outside function is: $a</p>"
?>

2. Global– A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. The global keyword is used to access a global variable from within a function:

<?php
$a = 9// global scope
function myTest() {
// using a inside this function will generate an error
echo "<p>Variable a inside function is: $a</p>";
}
myTest();
echo "<p>Variable a outside function is: $a</p>"
?>
  1. Static– When a function is executed, all of its variables are deleted. But if you want any variable not to be deleted, the static keyword is used when you first declare the variable:
<?php
function myTest() 
{
static $a = 0;
echo $a$a++; 
}
myTest();
myTest();
myTest();
?>

Now that you know about the declaration of variables, let’s move ahead with the PHP Tutorial and have a look at the operators in PHP.

PHP Operators

Operators are used for performing different operations on variables. Let’s have a look at the different operators in PHP:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Array operators

Arithmetic Operators

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

Operator

Name

Example

Result

+

Addition

$a + $b

Sum of $a and $b

Subtraction

$a – $b

Difference of $a and $b

*

Multiplication

$a * $b

Product of $a and $b

/

Division

$a / $b

Quotient of $a and $b

%

Modulus

$a % $b

Remainder of $a divided by $b

**

Exponentiation

$a ** $b

Result of raising $a to the $b’th power

 

Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

Assignment

Similar to

Result

a = b

a = b

The left operand gets set to the value of the expression on the right.

a += b

a = a + b

Addition

a -= b

a = a – b

Subtraction

 

Comparison Operators

The PHP comparison operators are used to compare two numbers or strings

Operator

Name

Example

==

Equal

$a == $b

===

Identical

$a === $b

!=

Not equal

$a != $b

<> 

Not equal

$a <> $b

!==

Not identical

$a !== $b

> 

Greater than

$a > $b

< 

Less than

$a < $b

>=

Greater than or equal to

$a >= $b

<=

Less than or equal to

$a <= $b

 

Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator

Name

Example

and

And

True if both $a & $b are true

or

Or

True if either $a or $b are true

xor

Xor

True if either $a or $b are true, but not both

&&

And

True if both $a & $b are true

||

Or

True if either $a or $b are true

!

Not

True if $a is not true

 

Array Operators

The PHP array operators are used to compare arrays.

Operator 

Name

Example

+

Union

$a + $b

==

Equality

$a == $b

===

Identity

$a === $b

!=

Inequality

$a != $b

<> 

Inequality

$a <> $b

!==

Non-identity

$a !== $b

 Now let’s move ahead with our PHP Tutorial and have a look at the various OOP concepts in PHP.