Thu. Nov 21st, 2024

sarveshpathak.com

Code Snippets, Tutorials, Articles, Technical Stuff

PHP Array

3 min read

An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values. Here will understand JSON Array, In_array, and Array Sort with examples in PHP.

PHP JSON Array

The json_encode() function is used to encode a value to JSON format.

The json_decode() function is used to decode a JSON object into a PHP object or an associative array.

PHP JSON Array Merge

Merging one or more JSON arrays using PHP can be done in various ways. For example, the merge can be done by using the PHP array_merge() function or by pushing each JSON array into a target array.

In this example, we are having two JSON objects merge together. These objects will be decoded into an associative array and encoded after the array merge.

Example of JSON Array

<?php
$json1 = '{
	"id": "#001",
    "Product": "Soap",
    "Qty Available": 122,
    "Total Sales": 500
}';

$json2 = '{
    "id": "#001",
    "Product": "Shampoo",
    "Qty Available": 1212,
    "Total Sales": 5798
}';
$Product[] = json_decode($json1, true);
$Product[] = json_decode($json2, true);
$json_merge = json_encode($Product);
?>

<h4>Two JSON String:</h4>
<div>
	<div>$json1 = <?php echo $json1; ?></div>
	<div>$json2 = <?php echo $json2; ?></div>
</div>
<h4>Output:</h4>
<div><?php echo $json_merge; ?></div>

Result JSON Array

PHP Array 3

PHP in_array

In PHP, in_array() is used to check whether a value or subarray is part of a given master array or not. If the given value or sub-array exists in the master array, then in_array() will return TRUE, or false otherwise.

PHP in_array Syntax and Parameters

<?php in_array($data_to_search, $master_array, $strict_search_flag); ?>

Parameters of PHP in_array() Function

  • $data_to_search – It could be a string, int, or an array. But, before PHP version 4.2.0, array data are not allowed for this first parameter of in_array().
  • $master_array – It accepts an array considered as a master or collection, among which we need to search for a given data.
  • $strict_search_flag – This optional parameter will have boolean values. If TRUE this function will do a strict search by comparing the data types, otherwise doing a loose search, if it is FALSE.

PHP in_array() Function Code Example

<?php
echo in_array('3', array(
    true,
    "one",
    "two",
    "three"
));
?>

In the above program, array_key_exists() will return TRUE

Other PHP Functions for Searching Arrays

PHP includes some other functions to search for a keyword or string over a master array as like as PHP in_array. These functions are,

  • array_key_exists()
  • array_search()

PHP Key Matching using array_key_exists()

We have seen that PHP in_array() function returns TRUE if there is a match found between the given data and the values of the master array. Similarly, array_key_exists() will do the same for searching keys or indices if the master array is an associative array.

Example of array_key_exists()

<?php
$master_assoc_array = array(
    "id" => 1000,
    "name" => "PHP"
);
echo array_key_exists("name", $master_assoc_array);
?>

In the above program, array_key_exists() will return TRUE

array_search() in PHP

PHP array_search() will return the corresponding index of the entry with which the match is found, whereas, in_array() returns the boolean value TRUE, instead

Example array_search() in PHP

<?php
$master_array = array(
    "1",
    "2",
    "3"
);
echo "Array index of 'three 3' is " . array_search("3", $master_array);
?>

Output array_search() in PHP

Array index of 'three 3' is 2

PHP Array Sort

Sorting an array that includes several varieties of conditions based on which the group of elements of the array will be ordered. Based on these conditions sorting is classified into many types, for example, key-based sorting, value-based sorting, natural ordering and etc.

PHP provides a list of inbuilt functions to perform these types of sorting functionalities based on various conditions required. These are,

  1. sort() – sorts an array in ascending order; it has two arguments which are the array to be sorted and the sorting options. This second argument is optional, if nothing is specified, then the default value will be SORT_REGULAR. Let us see, all possible values of these sorts of option arguments in detail, later in this article.
  2. rsort() – This function accepts the same set of arguments as similar to sort(), but sorting will be done in reverse order.
  3. asort() – It is used to sort the elements of an array in ascending order like sort() function. But, it preserves the key indices as it is after sorting.
  4. arsort() – It preserves the key-value correlation after performing the sort operations in reverse order.
  5. usort() – Instead of sort options, usort() accepts a callback functions name which will be called for each element of the array and apply some condition. Based on the integer values returned by this function, sorting will be done.
  6. uasort() – It is the combination of usort() and asort() by preserving array key indices as it is after sorting with the callback function defined by the user.
  7. array_multisort()  – This function is used to perform a sort over multiple arrays at a time. It is also used to sort the multi-dimensional array by specifying sort options.
  8. natsort() – The above PHP sorting functions listed here will order the elements of an array based on the standard way of ordering. But natsort(), is used to perform sorting as like as how a person can sort it manually.
  9. natcasesort() – This is similar to natsort()  but is being used in a case-insensitive manner.

The classifications of PHP sorting functions listed above are used to order PHP array-based values. Some more functions are there in PHP to sort an array based on keys. These are,

  1. ksort() – It is as like as sort() which will sort array elements in ascending order, but, based on key instead.
  2. krsort() – This function is used to sort an array based on its key but in reverse order.
  3. uksort() – Combination of ksort() and usort() to perform key-based sorting with user-defined call back function specified while invoking this method.

So, these are the PHP array sort functions to order the elements with several possible conditions. Now we need to know about the sort flag option values and the behavior of sorting based on these values.

  1. SORT_REGULAR – This is the default option if nothing is specified for the above sorting functions. For this option, the data type of array element will be taken as it is for sorting without any modification.
  2. SORT_NUMERIC – As per the name of this option, it will allow sorting numerically.
  3. SORT_STRING – By specifying this flag option, a will be sorted in alphabetical order.
  4. SORT_NATURAL – This will provide a manual sorting result.
  5. SORT_FLAG_CASE – If this flag is on, then the alphabetical ordering will be done in a case-insensitive manner.
  6. SORT_LOCALE_STRING – This flag will allow sorting alphabetically based on the language configured or specified by the set locale() function currently

PHP Array Sort: Example

<?php
$rollNumbers = array(
    "23",
    "67",
    "59",
    "789",
    "12"
);
sort($rollNumbers, SORT_STRING);
echo "sort() results<br/>";
print "<PRE>";
print_r($rollNumbers);

print "</PRE>";
?>

In this program, the sort() function is used to order the roll numbers array in a standard format. By specifying the sort option as SORT_STRING, all the elements will be sorted alphabetically.

PHP Array Sort Example: Output

 Sort array Output Array
(
    [0] => 12
    [1] => 23
    [2] => 59
    [3] => 67
    [4] => 789
)

About Post Author

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.