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";
}
?>