Category Archives: Php Tutorial

PHP Sort Array without using built in function

We can write our own program to sort array in PHP without using built in functions like – sort(), rsort().

Example

";
print_r($array);


for($i = 0; $ < count($array); $i ++) {
    for($j = 0; $j < count($array)-1; $j ++){

        if($array[$j] > $array[$j+1]) {
            $temp = $array[$j+1];
            $array[$j+1]=$array[$j];
            $array[$j]=$temp;
        }       
    }
}

echo "Array After Sorting: ";
echo "
"; print_r($array); ?>

PHP Objects


PHP Objects: Like other programming languages Java,VB.Net,C# etc php also supports object oriented related concepts.Here we will learn classes and objects conceps in genenral.
Class is a blueprint for object creation and also we can say that object is a real world entity which has state and properties. For Example a bus class may contain speed ,color etc properties by which we can differentiate any other object from bus.
/p>


PHP Objects | Example

Before going deeper into php oops programming let us take a brief tour for oops concepts.

  1. Class
  2. Object
  3. Member Variable
  4. Member Function
  5. Inheritance

How to define PHP classes

Here is the example how to define and use simple class in php.

Example




myfun( 12, 2);
?>


Warning: Invalid argument supplied for foreach() in Php


Warning: Invalid argument supplied for foreach() in Php: This warning comes when you are not passing array to foreach. To fix this warning you can use is_array to check the argument type supplied to foreach. Here is an example – How to fix Warning: Invalid argument supplied for foreach().


Warning: Invalid argument supplied for foreach() in Php

Add the is_array() method to fix the warning –

Warning: Invalid argument supplied for foreach()

$array = array("John", "Rimmy", "Kelly");
//now add the following check 
if(is_array($array)){
foreach($array as $data){
echo $data;
}

}

The above check will fix your problem.

PHP Check that variable is an array


PHP Check that variable is an array : PHP function is_array is used to check a variable whether it is array or not. it accepts one parameter as variable and finds it is array or not. Returns true if the variable is array else it returns false. Here we are going to explain this function with example –


PHP Check that variable is an array

Here is an example of how to check a variable is array or not –

PHP Check that variable is an array Example 1

$array = array('a', 'b', 'c');

if(is_array($array)){
echo "This is array.";
}else{
echo "This is not array.";
}
//will print - This is array

The above example will print – This is array because we passed array variable to check.

Now lets go with another example which is not array

PHP Check that variable is an array Example 1

$str = "abcd";

if(is_array($str)){
echo "This is array.";
}else{
echo "This is not array.";
}
//will print - This is not array

The above example will print – This is not array because we passed string variable to check and this function will refurn false so it will go in else condition.

PHP str_pad function


PHP str_pad function : Is used to pad a string to new length with another string. This function basically pads the string to the left, right or both side of the string with a string. It accepts the string as input parameter and returns the padded string with new length. We are going to explain the str_pad function with example and demo.


PHP str_pad function Syntax

The Syntax for the str_pad is given below-

PHP str_pad function Syntax

str_pad(string,length,pad_str,pad_type);

Parameters

The Input parameters are –

  • string : String to be padded
  • length : New length of string. It should be more than the original length of the string.
  • pad_str : It’s optional. This is string to be added as pad. If you do not add this option by default whitespace will be added.
  • pad_type :It’s optional. This decides which side to add pad – Left, Right or Both Side. Available options are –

    • STR_PAD_BOTH : Add pad to both sides.


    • STR_PAD_LEFT : Add pad to left side.


    • STR_PAD_RIGHT : Add pad to right side.

Output

Returns the padded string.

Technical Requirements

Technical requirements are –

PHP Version : 4.01

PHP str_pad function Example

Here is very basic example of str_pad function-

PHP str_pad function Example:

$string = "Welcome to Tutorialsplane.";
$paddedString = str_pad($string,30,'*',STR_PAD_RIGHT);
echo $paddedString;

Try it Β»

If you run the above example it will produce output like this –

PHP str_pad function Example

PHP number_format Function


PHP number_format Function : This function is used to format a number with grouped thousand. This function accepts one, two or four parameter not three. This function is important when you are working with the numbers. For example if you are working with price and you want to format numbers up to two digits of decimal, you can use number_format() function. Suppose you have a variable $price = β€œ98”; if you use the function echo $formattedPrice = format_number($price,2); it will print 98.00.
We are going to describe this function with example and demo.


PHP number_format Function Syntax

Here is syntax of number_format Function

PHP number_format Function Syntax

number_format(number,decimals,dec_point,separator)

Parameters

  • number : The number you want to format. If other parameters are not set it will number with no decimal points and use thousand separator comma(,).
  • decimals : Used to set decimal points. Number will be formatted with decimal points.
  • dec_point : Separator for decimal point.
  • separator : Specifies the string for thousand separator.

Return Value

Returns the formatted number on the basis of the input parameters.

Technical Requirements

Php Version : 4+

PHP number_format Function Example 1

Here is very basic example with single parameter ie. number. PHP format number with commas is most common question here is the example of format number with comma –

PHP format number with commas

$number = "55789.99";
$formattedNumber = number_format($number);
echo $formattedNumber ;

Try it Β»

When you run the above example will produce the following output-

PHP number_format Function

PHP number_format Function Example 2

Here is example with single two parameters ie. number and decimal. PHP format number to 2 decimal places is also most common used example. Here is the example of format number with decimal –

PHP format number to 2 decimal places

$number = "55789.99";
$formattedNumber = number_format($number,2);
echo $formattedNumber ;

Try it Β»

When you run the above example will produce the following output-

PHP number_format Function Example

PHP number_format Function Example 3

Here is example with decimal point and separator –

Separator And String for Thousand Separator

$number = "55789.99";
$formattedNumber = number_format($number,2,',',' ');
echo $formattedNumber ;

Try it Β»

When you run the above example will produce the following output-

PHP number_format Function

In the above example there is comma instead of dot and a space separator in thousand.

PHP Implode function


PHP Implode function – It converts array into string. This function accepts array elements and returns the string of elements separated by delimiter. The function explode is reverse of the implode function. Both implode and explode functions are frequently used functions in php. We are going to describe the implode function with example and demo.


PHP Implode function Syntax

PHP Implode function Syntax

implode(separator, array);

Input Parameters

  • separator : Is used to put separator between array element you can pass null as β€œβ€ if do not want to put anything between elements.
  • array : Array you want to convert to string.

Return value

It returns string.

Technical Requirement-

PHP Version : 4+

Let us understand implode function with examples.

PHP Implode function Example

Here is very basic example –

PHP implode example

$array = array('a','b','c','d');
$string = implode(" ", $array);
echo $string;

Try it Β»

In the above example array elements converted into string by separator space. The above example will produce the following outut-

PHP Implode function Example

PHP implode array comma separated Example

Here is another example with separator comma β€œ,” –

PHP implode array comma separated

$array = array('a','b','c','d');
$string = implode(",", $array);
echo $string;

Try it Β»

The above example will produce following output-

PHP Implode function Example

PHP implode array pipe separated Example

Here is another example with separator pipepline β€œ|” –

PHP implode array separator pipeline β€œ|” Example

$array = array('a','b','c','d');
$string = implode("|", $array);
echo $string;

Try it Β»

The example will convert the array elements to string by pipeline separator. Here is the output of the above example –

PHP implode array comma separated string

If you want to perform reverse of this function use the function explode.

Note : PHP implode function is binary safe.

PHP htmlspecialchars Function


PHP htmlspecialchars Function : It converts Special Characters to HTML entities. This function returns the converted result as string. This function has its own significance and used frequently. The opposite of this functions is htmlspecialchars_decode(). We are going to explain this example with example and demo.

Let us understand the htmlspecialchars with very basic example – We have some raw data like this – <b>Hi it’s me John</b> now what would happen when user see form data on browser it will show something bold string like this – Hi it’s me John which is wrong because it should show output like this – <b>Hi it’s me John</b> . Now to fix this problem convert HTML tags to its equivalent entities. This is done by using the function htmlspecialchars().


PHP htmlspecialchars Function Syntax

It Converts the following HTML Characters only –

  • &(ampersand) = &
  • ” (double quote) = "
  • β€˜ (single quote) = '
  • < (less than) = <
  • > (greater than) = >

Here is syntax for the function htmlspecialchars –

Syntax

htmlspecialchars(string,flags,char-set,double_encode)

Input Parameters

  • string: String to be converted.
  • flag:flag is optional . This is basically used to specify how to handle the quotes and which document type use.

Here are following flags available-

  • ENT_COMPAT : This is default. Encodes only Double Quotes
  • ENT_QUOTES : This Encodes Both Single and Double Quotes.
  • ENT_NOQUOTES : Encodes neither Single nor Double Quotes.
  • ENT_IGNORE : Ignore invalid code unit sequences instead of returning empty string.
  • ENT_SUBSTITUTE : Replace invalid code unit sequence with a unicode replacement
    charecter U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string
  • ENT_DISALLOWED : Replace invalid code points in the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD;.
  • ENT_HTML401 : Handle code as HTML 4.01.
  • ENT_XML1 : Handle code as XML 1.
  • ENT_XHTML : Handle code as XHTML.
  • ENT_HTML5 : Handle code as HTML 5.
  • char-set: This is optional parameter. This is basically used to decide which character set to use.
    • UTF-8 : This is Default ASCII Compatible Multi byte 8-bit Unicode.
    • ISO-8859-1 : Western European, Latin-1.
    • ISO-8859-15 : Western European, Latin-9
    • cp866: DOS-specific Cyrillic charset
    • cp1251 : Windows-specific Cyrillic charset.
    • cp1252 : Windows specific charset for Western European
    • KOI8-R : Russian.
    • BIG5 : Traditional Chinese, Specially used in Taiwan.
    • GB2312 : National standard character set.
    • BIG5-HKSCS : Traditional Chinese.
    • Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese
    • EUC-JP :Japanese
    • MacRoman : Charset that was used by Mac OS.
  • double_encode: This is optional parameter which decides whether to encode existing htmlentitis or not. It accepts TRUE and FALSE as parameter.
    • TRUE: Encode Everything.
    • FALSE: Do not encode existing htmlentities.

Return Values

This function returns the encodeed string.

Php Version

Supports in php 4+

PHP htmlspecialchars function example

PHP htmlspecialchars function example with single quotes

$string = "Hi it's me John";
echo htmlspecialchars($string);

Try it Β»

Above Example will produce following output-

HTML Output

PHP htmlspecialchars function example

Browser Output

PHP htmlspecialchars function example

PHP htmlspecialchars function example

PHP htmlspecialchars function example with double quotes

$string = '"Hello World"';
echo htmlspecialchars($string);

Try it Β»

HTML Output

PHP htmlspecialchars function example

Browser Output

PHP htmlspecialchars example

Note : Using htmlspecialchars is good practice. Use this when working with data output or working with characters and entities.

More About htmlspecialchars Funtion

Let’s have some more information about this function.


PHP htmlspecialchars vs htmlentities

The difference between htmlspecialchars and entities is given below-

  • htmlentities β€” Converts/Encodes all applicable characters to HTML entities.
  • htmlspecialchars β€” Converts/Encodes only special characters to HTML entities.
  • htmlspecialchars does not converts all characters having their html equivalent.
  • If output is XML you can’t use HTML entities in a XML file.
  • htmlentities converts more characters than htmlspecialshars so htmlspecialchars is more efficient.
  • If your page have encoding ASCII or LATIN-1 use htmlentities else use htmlspecialchars.

Read full documentations about htmlentities with example and demo – htmlentities

Tip : Use both the functions where they are needed because both have different efficiency.

PHP htmlspecialchars reverse

If want to perform reverse operation of htmlspecialchars use – htmlspecialchars_decode.

Try Video Demo – All In One Video for this method –

PHP htmlspcialchars function Video Demo –

PHP htmlspecialchars_decode Function


PHP htmlspecialchars_decode Function : It converts Some HTML entities to its characters equivalent. This function is opposite of htmlspecialchars() function. We are going to explain this example with example and demo.


PHP htmlspecialchars_decode Function Syntax

It Converts the following entities only –

  • & = &(ampersand)
  • " = ” (double quote)
  • ' = β€˜ (single quote)
  • < = < (less than)
  • > = > (greater than)

Here is syntax for the function htmlspecialchars_decode –

Syntax

htmlspecialchars_decode(string,flags)

Input Parameters

  • string: String to be converted.
  • flag:flag is optional . This is basically used to specify how to handle the quotes and which document type use.

Here are following flags available-

  • ENT_COMPAT : This is default. Converts only Double Quotes
  • ENT_QUOTES : This Converts Both Single and Double Quotes.
  • ENT_NOQUOTES : Converts neither Single nor Double Quotes.
  • ENT_HTML401 : Handle code as HTML 4.01.
  • ENT_XML1 : Handle code as XML 1.
  • ENT_XHTML : Handle code as XHTML.
  • ENT_HTML5 : Handle code as HTML 5.

Return Values

This function returns the converted string.

PHP htmlspecialchars_decode Function Example-

Let’s understand the above function with example and demo –

PHP htmlspecialchars_decode

$string = "

Hello World -> "

"; echo htmlspecialchars_decode($string);

Try it Β»

The above example will produce the following output-

Html Output

PHP htmlspecialchars_decode function

Browser Output

PHP htmlspecialchars_decode function


More Example

Let’s have a look over more example and demo here. Here we will explain example with flags.

PHP htmlspecialchars_decode

$string = "

Hello ' World ->Learn & More Here "

"; echo htmlspecialchars_decode($string, ENT_COMPAT)."
"; echo htmlspecialchars_decode($string, ENT_QUOTES)."
"; echo htmlspecialchars_decode($string, ENT_NOQUOTES)."
";

Try it Β»

The above example will produce the following output-

Html Output

PHP htmlspecialchars_decode example

Browser Output

Browser Output