Basics of WEB IV
Basics of WEB IV
Basics of WEB IV
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.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional 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:
Output:
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:
Output:
Output:
Output:
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
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Output:
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:
Output:
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:
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)
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.
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:
array_splice($fruits, 0, 1);
print_r($fruits);
$codes = [
'red' => 'apple',
'orange' => 'orange',
'blue' => 'blueberry'];
array_splice($codes, 0, 1);
print_r($codes);
Output:
Array
(
[orange] => orange
[blue] => blueberry
)
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.
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
)
Syntax
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:
Syntax
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 )
Syntax
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 )
)
Syntax
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
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
Syntax
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
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
Syntax
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
EXAMPLE
<?php
// Declare an array
$arr = array("Welcome","to", "Reva",
"A", "Computer","Science","Portal");
?>
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
?>
Output:
{"name":"GFG","0":{"email":"abc@gfg.com","mobile":"XXXXXXXXXX"}}
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
6. json_decode() Function
7. unserialize() Function
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.
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
)
The following example illustrates the working of the str_split() function to convert string to array in
PHP.
<?php
// define a string
$my_array1 = str_split($my_string);
print_r($my_array1); // s, a, m, p, l, e, s, t, r, i, n, g
print("<br><br>");
// length = 3
?>
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.
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.
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:
Output:
Array
[2] => is
[3] => your
Input:
Output:
Array
Input:
Output:
Array
The following example illustrates the working of the explode() function to convert string to array in
PHP.
<?php
// define a string
?>
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.
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.
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
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.
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
?>
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.
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.
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_array = [];
$my_array[] = $my_string[$i];
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.
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.
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_array = json_decode($my_string);
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.
Parameters
$options (optional): This is an optional parameter that represents the options that can be
provided to this function.
Return Value
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";}';
$my_array = unserialize($my_string);
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.
<?php
// Creating multidimensional
// array
$myarray = array(
Output:
Array
(
[0] => Array
(
[0] => Ankit
[1] => Ram
[2] => Shyam
)
)
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
print_r($marks);
?>
Output:
Display Marks:
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
[FOL] => 74
)
)
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
Output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
)
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
// Creating multidimensional
// associative array
$marks = array(
?>
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:
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>";
}
?>
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.
Writing to a file
There are two function available for writing to a file
o fwrite( ) and fputs
fputs( ) is an alias for fwrite( )
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.
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' ];
fclose( $fp );
?>
</body>
</html>
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)
Automatically strips out any php or html tags that are not specifically allowed
<?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 );
fclose( $fp );
?>
</table>
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.
Dumps files contents from the file pointer position to the end to standard output.
Same as readfile but instead of echoing content to standard out it turns the content into an array.
<?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>";
</table>
<a href="guestBookSign.php">Sign the Book Again</a>
fread reads a specific number of bytes from the file pointer or to the end, whichever comes first.
Deletes a file
rewind( 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.
fp is the file that the lock is being established with and operation is the type of lock that is being
established.
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.