Nothing Special   »   [go: up one dir, main page]

Basics of WEB IV

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

PHP Programming

PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

Creating Arrays in PHP


1. PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

1. $season=array("summer","winter","spring","autumn");

2nd way:

1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>

Output:

Season are: summer, winter, spring and autumn


File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>

Output:

Season are: summer, winter, spring and autumn

2. PHP Associative Array


We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

2nd way:

1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";

Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

Accessing Elements of Array


File: array1.php
1. <?php
2. $size=array("Big","Medium","Short");
3. echo "Size: $size[0], $size[1] and $size[2]";
4. ?>

Output:

Size: Big, Medium and Short


File: array2.php
1. <?php
2. $size[0]="Big";
3. $size[1]="Medium";
4. $size[2]="Short";
5. echo "Size: $size[0], $size[1] and $size[2]";
6. ?>

Output:

Size: Big, Medium and Short


Traversing PHP Indexed Array - Iterating Array with
Numeric index
We can easily traverse array in PHP using foreach loop. Let's see a simple example to
traverse all the elements of PHP array.

File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>

Output:
Size is: Big
Size is: Medium
Size is: Short

Count Length of PHP Indexed Array


PHP provides count() function which returns length of an array.

1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>

Output:

PHP Associative Array - Iterating Array Elements


PHP allows you to associate name/label with each array elements in PHP using => symbol.
Such way, you can easily remember the element because each element is represented by
label than an incremented number.

Definition
There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

2nd way:

1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";

Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>
Output:

Sonoo salary: 550000


Vimal salary: 250000
Ratan salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="550000";
3. $salary["Vimal"]="250000";
4. $salary["Ratan"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
7. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
8. ?>

Output:

Sonoo salary: 550000


Vimal salary: 250000
Ratan salary: 200000

Traversing PHP Associative Array


By the help of PHP for each loop, we can easily traverse the elements of PHP associative
array.

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>

Output:

Key: Sonoo Value: 550000


Key: Vimal Value: 250000
Key: Ratan Value: 200000
Insert new item in array on any position in PHP

New item in an array can be inserted with the help of array_splice()


function of PHP. This function removes a portion of an array and
replaces it with something else. If offset and length are such that
nothing is removed, then the elements from the replacement array
are inserted in the place specified by the offset.
Syntax:
array array_splice ($input, $offset [, $length [, $replacement]])
Parameters:
This function takes four parameters out of which 2 are mandatory
and 2 are optional:
$input: This parameter takes the value of an array on which
operations need to be performed.
$offset: If this parameter is positive then the start of the removed
portion is at that position from the beginning of the input array and if
this parameter is negative then it starts that far from the end of the
input array.
$length: (optional) If this parameter is omitted then it removes
everything from offset to the end of the array.
If length is specified and is positive, then many elements will be
removed.If length is specified and is negative then the end of the
removed portion will be that many elements from the end of the
array.If length is specified and is zero, no elements will be removed.
$replacement: (optional) This parameter is an optional parameter
which takes value as an array and if this replacement array is
specified, then the removed elements are replaced with elements
from this replacement array.
Return Value:
It returns the last value of the array, shortening the array by one
element. Note that keys in replacement array are not preserved.
Program
<?php
//Original Array on which operations is to be perform
$original_array = array( '1', '2', '3', '4', '5' );
echo 'Original array : ';
foreach ($original_array as $x)
{
echo "$x ";
}
echo "\n";
//value of new item $inserted_value = '11';
//value of position at which insertion is to be done $position = 2;
//array_splice() function
array_splice( $original_array, $position, 0, $inserted_value );
echo "After inserting 11 in the array is : ";
foreach ($original_array as $x)
{
echo "$x ";
} ?>

Output
Original array : 1 2 3 4 5
After inserting 11 in the array is : 1 2 11 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(1)

Array - Deleting elements from array in PHP


The easiest way to delete an element from an array in PHP is by using unset().

$fruits = ['apple', 'orange', 'pear'];


unset($fruits[1]);

However, note that this does not re-index the array, so $fruits[2] will remain
‘pear’. We’ll go into more detail about that and explore some other options
below.

Deleting a Single Element

To delete a single element from an array, you can use:


The array_splice() function, which removes the element based on its index
and reindexes the array.
The unset() function, which removes the element by its key and removes the
element’s index.

The array_splice() Function


The array_splice() function is the most versatile and direct solution for
deleting an element from both indexed arrays and associative arrays (with
key-value pairs). We call the array_splice() function with three arguments:

the array,
the offset of the element to be removed, and
the number of elements you want to remove.
Given an indexed array, you can remove the element at index 0 and specify
only one element to be removed:

$fruits = ['apple', 'orange', 'pear'];


// remove the first element and only remove one

array_splice($fruits, 0, 1);
print_r($fruits);

This will output:


Click to Copy
Array
(
[0] => orange
[1] => pear
)

The array_splice() function is a convenient method to delete a single element


from an associative array, as you can remove an element based on its offset
rather than its key or value. For example:

$codes = [
'red' => 'apple',
'orange' => 'orange',
'blue' => 'blueberry'];
array_splice($codes, 0, 1);
print_r($codes);
Output:

Array
(
[orange] => orange
[blue] => blueberry
)

The unset() Function


Use unset() to remove an element by its key.

$fruits = ['apple', 'orange', 'pear'];


// remove the second element
unset($fruits[1]);
print_r($fruits);

The output is:


Array
(
[0] => apple
[2] => pear
)

Removing an element from an array using the unset() function results in the
element’s index being removed too. If the consecutive numerical indexing of
your array is important, you can follow the unset() function with the
array_values() function. The array_values() function doesn’t update the array
but returns a new array, so we need to create a variable to store the value of
array_values().
Here we reindex the array with array_values() so that pear is at index one:
// array_values() - converts keys to numerical values
$reset = array_values($fruits);
print_r($reset);
The output is:
Array
(
[0] => apple
[1] => pear
)
Note that using the array_values() function with an associative array will
return a new array with numeric keys, for example:
Click to Copy
$colors = [
'red' => 'apple',
'orange' => 'orange',
'blue' => 'blueberry'];
$colorsTest = array_values($colors);
print_r($colorsTest);
T
he output is:

Array
(
[0] => apple
[1] => orange
[2] => blueberry
)

If you want to delete an element from an array but you only know its value,
you can use array_search() to find the key of the element, and then use unset()
to remove the key-value pair. Note that if there are duplicate elements in the
array, array_search() will only return the first match.

$colors = [ 'red' => 'apple',


'orange' => 'orange',
'blue' => 'blueberry'];
$findKey = array_search('apple', $colors);
print_r($findKey);
The output is:
red

Now we use unset() to remove the key-value pair from the array:
Click to Copy
unset($colors['red']);
print_r($colors);

Output:
Array
(
[orange] => orange
[blue] => blueberry
)

Deleting Multiple Elements


To delete multiple nonconsecutive elements from an array, you can use:
The array_diff() function, which deletes elements and their indices from an
indexed or associative array with the values as input.
The array_diff_key() function, which removes elements from an associative
array using their keys as arguments.
The array_diff() Function
In this example, we call array_diff() on an indexed array to create a new
array without John, Sue, and Sean:

$names = ['John', 'Mary', 'Sue', 'Daniel', 'Sean'];$newNames =


array_diff($names, ['John', 'Sue', 'Sean']);
print_r($newNames);
The output contains the remaining elements but the indexes are no longer
sequential:
Click to Copy
Array
(
[1] => Mary
[3] => Daniel
)
As with unset(), you can use array_values() to reindex the output:
Click to Copy
Array
(
[0] => Mary
[1] => Daniel
)
We can use array_diff() on an associative array to create a new array with
elements removed based on their values. This is handy in cases where you
aren’t sure of the keys of the elements to be removed.
Click to Copy
$jobs = [
'Lawyer' => 'John',
'Teacher' => 'Mary',
'Chef' => 'Sue',
'Driver' => 'Daniel',
'Doctor' => 'Sean'];
$newJobs = array_diff($jobs, ['John', 'Sue', 'Sean']);print_r($newJobs);
Output:
Click to Copy
Array
(
[Teacher] => Mary
[Driver] => Daniel
)

The array_diff_key() Function


Use the array_diff_key() function when you want to delete several elements
from an array using their key values.
Click to Copy
$times = [
'8:00' => 'morning',
'12:00' => 'noon',
'19:00' => 'night'];
// the values can be set to an empty string, or any character or
string$newTimes = array_diff_key($times, ['8:00' => '', '12:00' =>
'']);print_r($newTimes);
Output:
Array
(
[19:00] => night
)

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

1) PHP array() function


PHP array() function creates and returns an array. It allows you to create indexed,
associative and multidimensional arrays.

Syntax

1. array array ([ mixed $... ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>

Output:

Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function


PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>

Output:

Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:

Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )

3) PHP array_chunk() function


PHP array_chunk() function splits array into chunks. By using array_chunk() method, you
can divide array into many parts.

Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>

Output:

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

4) PHP count() function


PHP count() function counts all elements in an array.

Syntax

1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>

Output:

4
5) PHP sort() function
PHP sort() function sorts all the elements in an array.

Syntax

1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
summer
winter

6) PHP array_reverse() function


PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:

autumn
spring
winter
summer

7) PHP array_search() function


PHP array_search() function searches the specified value in an array. It returns key if
search is successful.

Syntax

1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>

Output:

8) PHP array_intersect() function


PHP array_intersect() function returns the intersection of two array. In other words, it
returns the matching elements of two array.

Syntax

1. array array_intersect ( array $array1 , array $array2 [, array $... ] )

Example

1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>

Output:

sonoo
smith

Converting an Array to String

we can use two methods to convert array to string.


Method 1: Using implode() function: The implode() method is an inbuilt function in PHP and is
used to join the elements of an array. The implode() method is an alias for PHP | join()
function and works exactly same as that of join() function.
Syntax:
string implode($separator, $array)

EXAMPLE
<?php

// Declare an array
$arr = array("Welcome","to", "Reva",
"A", "Computer","Science","Portal");

// Converting array elements into


// strings using implode function
echo implode(" ",$arr);

?>
Output:
Welcome to Reva A Computer Science Portal
Method 2: Using json_encode() Function: The json_encode() function is an inbuilt function in
PHP which is used to convert PHP array or object into JSON representation.
Syntax:
string json_encode( $value, $option, $depth )
Example:
<?php

// Declare multi-dimensional array


$value = array(
"name"=>"GFG",
array(
"email"=>"abc@gfg.com",
"mobile"=>"XXXXXXXXXX"
)
);

// Use json_encode() function


$json = json_encode($value);

// Display the output


echo($json);

?>
Output:
{"name":"GFG","0":{"email":"abc@gfg.com","mobile":"XXXXXXXXXX"}}

Converting String to Array

Following is the complete list of methods that can be used in PHP to convert a string to an array.

1. str_split() Function

2. explode("DELIMITER", STRING)

3. preg_split() Function

4. str_word_count() Function

5. Manually loop through the string

6. json_decode() Function

7. unserialize() Function

Different Methods to Convert String to Array in PHP

There are various approaches, including in-built functions and manual approaches that are used to
convert string to array in PHP.
1. str_split() Function

The first method in this list is str_split(). This is an in-built PHP method that is used to convert a string
into an array by breaking the string into smaller sub-strings of uniform length and storing them in an
array. It does not use any kind of separator, it just splits the string.

The syntax of the str_split() function is:

str_split($initial_string, $splitting_length)

Parameters

 $initial_string (mandatory): The first parameter you pass to this function is the string that has to
be converted into an array.

 $splitting_length (optional): The second parameter is an integer that represents how long the
parts of the strings will be after splitting. It is an optional parameter. If not passed, the function will
consider this length as 1 by default.

Return Value

This function returns an array that contains the pieces of the original string. If the length that is passed
to the function surpasses the length of the initial string, the function will return the whole string as one
element, whereas if the length integer is less than one, the function will return false.

Example

Input:

"Program"

Output:

Array

(
[0] => P

[1] => r

[2] => o

[3] => g

[4] => r

[5] => a

[6] => m

Input:

"Programming Language"

Output:

Array

[0] => Prog

[1] => ram

[2] => ming

[3] => Lang

[4] => uage

)
The following example illustrates the working of the str_split() function to convert string to array in
PHP.

<?php

// define a string

$my_string = 'Sample String';

// without passing length

// length = 1 (by default)

$my_array1 = str_split($my_string);

// print the array

echo "The array of default length elements is: ";

print_r($my_array1); // s, a, m, p, l, e, s, t, r, i, n, g

print("<br><br>");

// passing length as second argument

// length = 3

$my_array2 = str_split($my_string, 3);

// print the array

echo "The array of length 3 elements is: ";

print_r($my_array2); // sam, ple, str, ing

?>
In the above example, it initializes a variable $my_string1 with a string “Sample String”. It uses the
str_split() method to convert the string to an array. The following expression passes the string to this
method without passing the length argument.

$my_array1 = str_split($my_string);

By default, if you do not pass the length delimiter, it takes it as 1. So, it converts separate elements of
the string into array elements. And the following expression passes 3 as the length delimiter, which
converts the substring of length 3 into array elements.

$my_array2 = str_split($my_string, 3);

2. explode("DELIMITER", STRING);

The explode() function is another method of PHP that is used to convert a string into an array. Unlike
the str_split() function, this function uses a separator or delimiter that needs to be passed as an
argument to the function. This separator could be a comma (,), a dot (.), or anything. After splitting the
string into smaller substrings, this function stores them in an array and returns the array.

The syntax of the explode() function is

explode($separator, $initial_string, $no_of_elements)

Parameters
 $separator: The separator is a character that commands the explode() function to split the string
whenever it detects the separator and stores that substring in the array.

 $initial_name: The second parameter that is passed to this function is the string that has to be
converted into an array.

 $no_of_elements (optional): This is the last and an optional parameter that is passed to this
function. This parameter represents the number of strings in which it should split the original string.
This number can be positive, negative, or zero.

 Positive: If the passed integer is positive, then the array will store this many numbers of
elements. If you separate the string into more than N number of pieces regarding the delimiter, the
first N-1 elements remain the same, and the rest of the elements combine to form a single element.

 Zero: If the passed integer is 0, then the array will contain the whole string as a single element.

 Negative: If the passed integer is negative then the last N elements of the array will be cut off
and it will return the remaining elements.

Return Value

The explode() function returns an array that contains the string pieces as its elements.

Example

Input:

explode(“ “, “Hello, what is your name?")

Output:

Array

[0] => Hello,

[1] => What

[2] => is
[3] => your

[4] => name?

Input:

explode(“ “, “Hello, what is your name?", 3)

Output:

Array

[0] => Hello,

[1] => What

[2] => is your name?

Input:

explode(“ “, “Hello, what is your name?", -1)

Output:

Array

[0] => Hello,

[1] => What


[2] => is

[2] => your

The following example illustrates the working of the explode() function to convert string to array in
PHP.

<?php

// define a string

$my_string = 'red, green, blue';

// passing "," as the delimiter

$my_array1 = explode(",", $my_string);

// print the array

echo "The converted Sarray is: <br>";

print_r($my_array1); // red, green, blue

?>
In the above example, you are converting a string containing three colors separated by a comma to an
array. The comma “,” is passed to the explode() function as a delimiter to convert the string into array
elements.

3. preg_split() Function

The preg_split() is also an in-built PHP function that is used to convert a string into an array by
splitting it into smaller substrings. Just like the explode() function, it also uses a separator but the
separator in this function is a pattern of regular expressions. The length of substrings depends upon the
integer value known as a limit that is passed to this function.

The syntax of the preg_split() function is :

preg_split($pattern, $string, $limit, $flags)

Parameters

 $pattern: The pattern is a regular expression that determines what character is used as a
separator to split the string.

 $string: The second parameter that is passed to this function is the string that has to be
converted into an array.

 $limit (optional): The limit indicates the total number of substrings in which it will split the
string. If all the separators appear before the limit ends, the (limit-1) elements remain the same and
the rest of the elements combine to form the last element. If the limit is 0, then, it will return the
whole string as one single element. However, it is an optional parameter. If not mentioned, it will
consider the limit as -1 by default.

 $flags (optional): This is an optional parameter. If passed, it is used to bring some changes to
the array. In other words, the flag represents the condition on which the final array will be returned.
These options or conditions are:
 PREG_SPLIT_NO_EMPTY: This flag type is used to remove the empty string and the
non-empty strings will be returned.

 PREG_SPLIT_DELIM_CAPTURE: This flag type is used to get the delimiter in the


resulting array as well. If this flag is used, then the expression within the parenthesis will also be
captured as an array element.

 PREG_SPLIT_OFFSET_CAPTURE: This flag type makes the function return a pair as


an array element. The first part of the pair will be the substring and the next part of the pair will
be the index of the first character of the substring in the initial string.

Return Value

The preg_split() function returns an array containing the substrings as its elements, separated by the
pattern passed to the function.

The following example illustrates the working of the preg_split() function to convert string to array in
PHP.

<?php

// define a string

$my_string = 'hello';

// -1 -> no limit

$my_array = preg_split('//', $my_string , -1, PREG_SPLIT_NO_EMPTY);

// print the array

echo "The converted array is: <br>";

print_r($my_array); // h, e, l, l, o

?>
In the example depicted above, it converts the string “hello” into an array. It passes ‘-1’ as the limit
argument, so there is no limit. The “//” is passed as the pattern to convert separate characters of the
string into array elements.

4. str_word_count() Function

The str_word_count() function is another in-built function. It is not used to split the string, but it gives
information about the string, such as the number of characters in the string, and so on.

The syntax of the str_word_count() function is:

str_word_count ( $string , $returnVal, $chars )

Parameters

 $string: The first parameter that is passed to this function is the string that has to be converted
into an array.

 $returnVal (optional): This parameter indicates what the function will return. This is an optional
parameter and by default, it is 0. It can take three different kinds of values:

 0: It is also the value by default. If the returnVal parameter is set to 0, then the
function will return the total count of the number of words in the input string.

 1: If the returnVal parameter is set to 1, then the function will return an array
containing all the words of the string as its elements.
 2: If you set if the returnVal parameter to 2, then the function will return an array containing the
key-value pairs. The key will be the index of the word and the value will contain the word itself.

 $chars (optional): This is again an optional parameter that tells the string to consider the
character that is passed as a parameter to as a word as well.

Return Value

The return value of the function depends on the parameters that are discussed above.

The following example illustrates the working of the str_word_count() function to convert string to
array in PHP.

<?php

// define a string

$my_string = 'he2llo world';

// the character '2' will not be considered as word

$my_array1 = str_word_count($my_string, 1);

// print the array

echo "The converted array is: <br>";

print_r($my_array1); // he, llo, world

// the character '2' is passed as the third argument

$my_array2 = str_word_count($my_string, 1, 2);

// print the array

echo "<br><br>The converted array is: <br>";


print_r($my_array2); // he2llo, world

?>

In the above example, the string “he2llo world” contains a character ‘2’ which is not considered as a
word by default by the function str_word_count(). So, the following expression converts the string into
an array and ‘2’ is omitted.

$my_array1 = str_word_count($my_string, 1);

When you pass the character ‘2’ as the third argument to the str_count_world() function, then it is
considered as a word and included in the array.

5. Manually Loop Through the String

The next method in this list through which you can convert a string into an array is by manually
looping through the string. You will initialize a variable, let's say “i” as 0, and start a loop from ”i”
until “i” becomes less than the length of the string. Inside the loop, you will store each word of the
string in the array and increment the variable “i”.

The following example illustrates the manual approach using a for loop to convert string to array in
PHP.
<?php

// define a string

$my_string = 'hello world';

// declare an empty array

$my_array = [];

// traverse the string

for ($i = 0; $i < strlen($my_string); $i++) {

if ($my_string[$i] != " ") {

$my_array[] = $my_string[$i];

// print the array

echo "The converted array is: <br>";

print_r($my_array); // h, e, l, l, o, w, o, r, l, d

?>
In the above example, an empty array is initialized. The string “hello world” is traversed using a for
loop and each character of the string is inserted into the array.

6. json_decode() Function

The json_decode() function is used to decode a JSON encoded string. JSON stands for JavaScript
Object Notation. JSON is a standard format for exchanging or transferring data and is powered
by JavaScript. The JSON string usually represents the objects into data-value pairs.

The syntax of the json)decode() function is:

json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )

Parameters

 $json: This parameter represents the JSON string that has to be encoded into an array.

 $assoc: This parameter is of boolean data type. If it is true, then the function will convert the
encoded string into an array.

 $depth: It represents the depth of the recursion that will be used to decode the string.

 $options (optional): It includes bitmasks of JSON_OBJECT_AS_ARRAY,


JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR.

Return Value

This function returns the decoded JSON string. If the depth of the encoded string is deeper than the
specified depth limit of the recursion, this function will simply return NULL.
The following example illustrates the working of the json_decode() function to convert string to array
in PHP.

<?php

// define a string

$my_string = '{"h":2, "e":5, "l":4, "l":8, "o":10}';

// convert into array

$my_array = json_decode($my_string);

// print the array

echo "The converted array is: <br>";

var_dump($my_array);

?>

In the above example, the string “hello” is initialized in the JSON format. The function json_decode()
accepts this string as an argument, decodes it, and converts it into an array.

7. unserialize() Function


The unserialize() function is another in-built PHP function. It is just the opposite of the PHP serialize()
function. This function converts a serialized string that is passed as a parameter, back into its original
form i.e., an array.

The syntax of the unserialize() function is:

unserialize( $serialized_array, $options )

Parameters

 $string: This parameter is the serialized string that needs to be unserialized.

 $options (optional): This is an optional parameter that represents the options that can be
provided to this function.

Return Value

The return value could be a boolean, string, integer, float, or anything.

The following example illustrates the working of the unserialize() function to convert string to array in
PHP.

<?php

// define a string

$my_string = 'a:3:{i:0;s:1:"a";i:1;s:6:"sample";i:2;s:6:"string";}';

// convert into array

$my_array = unserialize($my_string);

// print the array

echo "The converted array is: <br>";

print_r($my_array);
?>

In the above example, a serialized string “ a sample string” is initialized. The unserialize() function
accepts this string as an argument and unserializes this string and converts it back to the original array.

Multidimensional Arrays in PHP


Multi-dimensional arrays are such type of arrays which stores an another array at each index instead
of single element. In other words, define multi-dimensional arrays as array of arrays. As the name
suggests, every element in this array can be an array and they can also hold other sub-arrays within.
Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.
Dimensions: Dimensions of multidimensional array indicates the number of indices needed to select
an element. For a two dimensional array two indices to select an element.
Two dimensional array: It is the simplest form of a multidimensional array. It can be created using
nested array. These type of arrays can be used to store any type of elements, but the index is always a
number. By default, the index starts with zero.
Syntax:
array (
array (elements...),
array (elements...),
...
)
Example:

<?php

// PHP program to create


// multidimensional array

// Creating multidimensional
// array
$myarray = array(

// Default key for each will


// start from 0
array("Ankit", "Ram", "Shyam"),
array("Unnao", "Trichy", "Kanpur")
);

// Display the array information


print_r($myarray);
?>

Output:
Array
(
[0] => Array
(
[0] => Ankit
[1] => Ram
[2] => Shyam
)

[1] => Array


(
[0] => Unnao
[1] => Trichy
[2] => Kanpur
)

)
Two dimensional associative array: Al associative array is similar to indexed array but instead of
linear storage (indexed storage), every value can be assigned with a user-defined key of string type.
Example:

<?php

// PHP program to creating two


// dimensional associative array
$marks = array(

// Ankit will act as key


"Ankit" => array(

// Subject and marks are


// the key value pair
"C" => 95,
"DCO" => 85,
"FOL" => 74,
),

// Ram will act as key


"Ram" => array(

// Subject and marks are


// the key value pair
"C" => 78,
"DCO" => 98,
"FOL" => 46,
),

// Anoop will act as key


"Anoop" => array(

// Subject and marks are


// the key value pair
"C" => 88,
"DCO" => 46,
"FOL" => 99,
),
);
echo "Display Marks: \n";

print_r($marks);
?>

Output:
Display Marks:
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
[FOL] => 74
)

[Ram] => Array


(
[C] => 78
[DCO] => 98
[FOL] => 46
)

[Anoop] => Array


(
[C] => 88
[DCO] => 46
[FOL] => 99
)

)
Three Dimensional Array: It is the form of multidimensional array. Initialization in Three-
Dimensional array is same as that of Two-dimensional arrays. The difference is as the number of
dimension increases so the number of nested braces will also increase.
Syntax:
array (
array (
array (elements...),
array (elements...),
...
),
array (
array (elements...),
array (elements...),
...
),
...
)

Example:

<?php

// PHP program to creating three


// dimensional array

// Create three nested array


$myarray = array(
array(
array(1, 2),
array(3, 4),
),
array(
array(5, 6),
array(7, 8),
),
);

// Display the array information


print_r($myarray);
?>

Output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
)

[1] => Array


(
[0] => 3
[1] => 4
)

[1] => Array


(
[0] => Array
(
[0] => 5
[1] => 6
)
[1] => Array
(
[0] => 7
[1] => 8
)

)
Accessing multidimensional array elements: There are mainly two ways to access
multidimensional array elements in PHP.
 Elements can be accessed using dimensions as array_name[‘first dimension’][‘second
dimension’].
 Elements can be accessed using for loop.
 Elements can be accessed using for each loop.
Example:

<?php

// PHP code to create


// multidimensional array

// Creating multidimensional
// associative array
$marks = array(

// Ankit will act as key


"Ankit" => array(

// Subject and marks are


// the key value pair
"C" => 95,
"DCO" => 85,
"FOL" => 74,
),

// Ram will act as key


"Ram" => array(

// Subject and marks are


// the key value pair
"C" => 78,
"DCO" => 98,
"FOL" => 46,
),

// Anoop will act as key


"Anoop" => array(

// Subject and marks are


// the key value pair
"C" => 88,
"DCO" => 46,
"FOL" => 99,
),
);

// Accessing the array element


// using dimensions

// It will display the marks of


// Ankit in C subject
echo $marks['Ankit']['C'] . "\n";

// Accessing array elements using for each loop


foreach($marks as $mark) {
echo $mark['C']. " ".$mark['DCO']." ".$mark['FOL']."\n";
}

?>

Output:
95
95 85 74
78 98 46
88 46 99
PHP - Two-dimensional Arrays - Travesing through multi dimentional Atrray
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).
First, take a look at the following table:

Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2
Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and column):
ExampleGet your own PHP Server
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for loop inside another for loop to get the elements of the $cars array (we still have
to point to the two indices):
Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

PHP File Handling

Saving and Retrieving Data


 Being a server side scripting language PHP has the advantage of have access to the servers file
system where data can be stored and retrieved by PHP scripts.
 This is not always a good option, especially when large amounts of data need to be used.
 In these cases databases will be better and easier to use.
Saving Data for Later
 Data can be stored from a PHP script in flat files or in databases.
o Flat files are simple text files that avoid the overhead of a database but are much more
difficult and inefficient to work with.
 Writing data to a flat file requires 3 steps:
o Open the file. If it doesn’t exist you will need to create it.
o Write data to the file
o Close the file
 Reading data from a file is almost the same
o Open the file and handle the situation where the file doesn’t exist
o Read from the file
o Close the file
 Opening a file
o Use the fopen( ) function
o The fopen( ) function requires the path and name of the file to be opened and a mode to
work in.

$fp = fopen( "path/file.ext", ‘mode’ );

 Require a specific mode to open in


 Allowed modes are:

Mode Mode Name Meaning

R Read Opens for reading starting at the beginning

R+ Read Opens for reading and writing starting at the beginning

W Write Opens for writing starting at the beginning, if the file exists, content is deleted, if it doesn’t
exist, it will be created

W+ Write Opened for writing and reading, starts at the beginning, if the file exists, content is deleted, if
it doesn’t exist, it will be created

X Cautious Open the file for writing, start at the beginning, if file exists it will NOT be opened
Write

X+ Cautious Open the file for writing and reading, start at the beginning, if file exists it will NOT be opened
Write

A Append Open the file for appending (writing only) If doesn’t exists, will be created
A+ Append Open the file for appending and reading, If doesn’t exists, will be created

B Binary Used with another mode to specify binary data being read or written (default mode)

T Text Used with other modes to specify reading or writing of text data

 A third parameter can also be used with the fopen( ) function called include_path which must be
Boolean
o This option tells PHP to search the include_path (specified in the php.ini file) for the file that
is being opened.
 With this option it is not necessary to specify a path to the file.
 A fourth option allows for files to be opened using http or ftp
o A file pointer ($fp) will be return from the fopen( ) function if it is able to open the
requested file in the requested mode.
o This file pointer will be using from that point forward to access the file.
o If the file cannot be opened $fp will be set to a value of false which can then be tested for.

@$fp = fopen( "path/filename.ext", ‘ab’ );


if( !$fp ) {
echo "Something went wrong";
exit;
}

Opening files through HTTP or FTP


 This ability is controlled through the allow_url_fopen parameter in the php.ini file.

Writing to a file
 There are two function available for writing to a file
o fwrite( ) and fputs
 fputs( ) is an alias for fwrite( )

fwrite( $fp, $outputvariable );

 A third parameter for fwrite( ) is also available that allows you to specify the length (amount) of
data to write out.
 You can obtain the length of a string by using the strlen( ) function.

fwrite( resource handle, string string, [, length] )


Closing a file
 To close a file you use the fclose( ) function

fclose( $fp );

 This function returns true if the file was closed successfully and false otherwise

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sign the Guest Book</title>
</head>

<body>
<h2>Sign the Guest Book</h2>
<form action="guestBookWrite.php" method="POST">
<table>
<tr>
<td>Your Name:</td>
<td>
<input type="text" name="name"/>
</td>
</tr>
<tr>
<td>Your Email address:</td>
<td>
<input type="text" name="email"/>
</td>
</tr>
<tr>
<td colspan="2">
Message:<br/>
<textarea name="message" rows="10" cols="40">
</textarea>
</td>
</tr>
</table>
<input type="submit" value="Sign the Guest Book"/>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Signed????</title>
</head>

<body>
<?php
$name = $_POST[ 'name' ];
$email = $_POST[ 'email' ];
$message = $_POST[ 'message' ];

if( empty( $name ) || empty( $email )|| empty( $message ) ) {


echo 'You did not complete the form.<br/>
Please <a href="guestBookSign.php">
try again</a></body></html>';
exit;
}

$fp = fopen( "guestBook.txt", 'ab' );


if( !$fp ) {
echo "The guest book file could not be
opened.</body></html>";
exit;
}

$fileoutput = date( 'H:i m-d-Y' )


. "\t" . $name
. "\t" . $email
. "\t" . $message . "\n";

fwrite( $fp, $fileoutput );

echo 'The guestbook has been signed.<br/>


<a href="">View the Guest Book</a>';

fclose( $fp );
?>
</body>
</html>

Reading from a file


 To read from a file it must be opened with fopen( ) first
 The feof( ) function can then be used to determine when the end of the file has been reached.
 Returns true when the file pointer has reached the end of the file
 Each part of the input file can then be read with the fgets( ), fgetss( ), or fgetcsv( ) functions.

fgets( resource fp, int length );

 Reads one line at a time from the file delimited by a new line character (\n)
 $fp is the handle to the file to be read from
 999 means that 998 bytes will be read maximum before it stops reading (1 byte for EOF)

fgetss( resource fp, int length, string [allowable_tags] );

 Automatically strips out any php or html tags that are not specifically allowed

fgetcsv( resource fp, int length, [, string delimter [,


string enclosure] ] )

 Breaks up input lines based on the supplied delimiter


o Results are returned in an array

<?php
@ $fp = fopen( "guestbook.txt", "r" );
if( !$fp ) {
echo "The guestbook file could not be
opened.</body></html>";
exit;
}

?>
<table>
<!--
Simple read that puts entire
line into a single row and cell
-->
<?php
$line = fgets( $fp, 999 );

while( !feof( $fp ) ) {


echo "<tr><td>$line</td></tr>";
$line = fgets( $fp, 999 );
}

fclose( $fp );
?>
</table>

Reading the Whole File


o The readfile( ), fpasstatementru( ), and file( ) functions can be used to read a files
entire contents at once.

int readfile( string filename, [int include_use_path [, resource context ] ] )

 The readfile( ) function opens the file, echos the contents to standard output (the browser), and
then closes the file. It returns the number of bytes read from the file.

boolean fpasstatementru( resource fp )

 Dumps files contents from the file pointer position to the end to standard output.

int file( string filename )

 Same as readfile but instead of echoing content to standard out it turns the content into an array.

Reading Single Characters


char fgetc( resource fp )

 Reads a single character at a time from the specified file.


 Will return the EOF character while the other read functions do not.

<?php
@ $fp = fopen( "guestbook.txt", "r" );
if( !$fp ) {
echo "The guestbook file could not be opened.</body></html>";
exit;
}
?>

<table>
<tr>
<th id="dateColumn">Date</th>
<th>Name</th>
<th>Email</th>
<th>Comment</th>
</tr>

<?php
$field = "";
$char = fgetc( $fp );

echo "<tr>";

while( !feof( $fp ) ) {


if( $char == "\t" ) {
echo "<td>$field</td>";
$field = "";
} elseif( $char == "\n" ) {
echo "<td>$field</td>";
$field = "";
echo "</tr>\n<tr>";
} else {
$field .= $char;
}
$char = fgetc( $fp );
}
?>

</table>
<a href="guestBookSign.php">Sign the Book Again</a>

Reading an Arbitrary Length


string fread( resource fp, int length )

 fread reads a specific number of bytes from the file pointer or to the end, whichever comes first.

Other Useful File Functions


boolean file_exists( string filename )

 Check if a file exists or not

int filesize( string filename)

 Returns the size of a given file in bytes

string n12br( string input )

 Converts newlines (\n) to html breaks (<br/>)

boolean unlink( string filename )

 Deletes a file

rewind( resource fp )

 Resets file position pointer to the beginning of a file

int fseek( resource fp, int offset [, int whence] )


 Set the file position pointer to a specific point within the file
 Whence is the point the move starts from
o SEEK_SET
 The beginning of the file
o SEEK_CUR
 The current position
o SEEK_END
 The end of the file

int ftell( resource fp )

 Returns the number of bytes from the beginning of the file to where the file pointer currently is
located.

Locking Files
 A common situation in a web app would be where two or more people are accessing a file at the
same time.
 To avoid corruption of the file the file should be locked
 Locks need to be established after the file is open but before any data has been read or written to
the file.

boolean flock( resource fp, int operation [, int


&wouldblock ] )

 fp is the file that the lock is being established with and operation is the type of lock that is being
established.

Value of Operation Meaning

LOCK_SH (1) Reading lock. The file can be shared with other readers

LOCK_EX (2) Writing lock. The file is exclusive and cannot be shared.

LOCK_UN (3) The existing lock is released.

LOCK_NB (4) Blocking is prevented while trying to establish the lock.

Problems with Flat Files


 Slow – most types of processing would require the reading of the entire file, taking much time, like
searching or sorting, and the problem grows worse as the file grows larger.
 Dealing with file locks and concurrent access is tricky and error prone
 Inserting, deleting, and updating data in the flat file is complicated as some type of file structure
must be invented and maintained like with fixed length records.
 Security is difficult. Permissions can be used to determine who can access the file but enforcing
security inside a single file is very troublesome.

You might also like