Welcome to Knowledge Base!

KB at your finger tips

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All

Web-PHP

PHP / array_merge — DevDocs

array_merge

(PHP 4, PHP 5, PHP 7, PHP 8)

array_merge Merge one or more arrays

Description

array_merge(array ...$arrays): array

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Parameters

arrays

Variable list of arrays to merge.

Return Values

Returns the resulting array. If called without any arguments, returns an empty array .

Changelog

Version Description
7.4.0 This function can now be called without any parameter. Formerly, at least one parameter has been required.

Examples

Example #1 array_merge() example

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Example #2 Simple array_merge() example

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

Don't forget that numeric keys will be renumbered!

Array
(
    [0] => data
)

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Example #3 array_merge() with non-array types

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

The above example will output:

    Array
    (
        [0] => foo
        [1] => bar
    )

See Also

  • array_merge_recursive() - Merge one or more arrays recursively
  • array_replace() - Replaces elements from passed arrays into the first array
  • array_combine() - Creates an array by using one array for keys and another for its values
  • array operators

PHP / array_merge_recursive — DevDocs

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_merge_recursive Merge one or more arrays recursively

Description

array_merge_recursive(array ...$arrays): array

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

Parameters

arrays

Variable list of arrays to recursively merge.

Return Values

An array of values resulted from merging the arguments together. If called without any arguments, returns an empty array .

Changelog

Version Description
7.4.0 This function can now be called without any parameter. Formerly, at least one parameter has been required.

Examples

Example #1 array_merge_recursive() example

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

See Also

  • array_merge() - Merge one or more arrays
  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively
Read article

PHP / array_multisort — DevDocs

array_multisort

(PHP 4, PHP 5, PHP 7, PHP 8)

array_multisort Sort multiple or multi-dimensional arrays

Description

array_multisort(
 array &$array1,
 mixed $array1_sort_order = SORT_ASC,
 mixed $array1_sort_flags = SORT_REGULAR,
 mixed ...$rest
): bool

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Associative ( string ) keys will be maintained, but numeric keys will be re-indexed.

Note :

If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.

Note :

Resets array's internal pointer to the first element.

Parameters

array1

An array being sorted.

array1_sort_order

The order used to sort the previous array argument. Either SORT_ASC to sort ascendingly or SORT_DESC to sort descendingly.

This argument can be swapped with array1_sort_flags or omitted entirely, in which case SORT_ASC is assumed.

array1_sort_flags

Sort options for the previous array argument:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed.

rest

More arrays, optionally followed by sort order and flags. Only elements corresponding to equivalent elements in previous arrays are compared. In other words, the sort is lexicographical.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Sorting multiple arrays

<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.

array(4) {
  [0]=> int(0)
  [1]=> int(10)
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(4)
  [1]=> int(1)
  [2]=> int(2)
  [3]=> int(3)
}

Example #2 Sorting multi-dimensional array

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Example #3 Sorting database results

For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.

Example data:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

The data as an array, called data . This would usually, for example, be obtained by looping with mysqli_fetch_assoc() .

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// you can use array_column() instead of the above code
$volume  = array_column($data, 'volume');
$edition = array_column($data, 'edition');

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

The dataset is now sorted, and will look like this:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Example #4 Case insensitive sorting

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive sort, force the sorting order to be determined by a lowercase copy of the original array.

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

The above example will output:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

See Also

  • usort() - Sort an array by values using a user-defined comparison function
  • The comparison of array sorting functions
Read article

PHP / array_pad — DevDocs

array_pad

(PHP 4, PHP 5, PHP 7, PHP 8)

array_pad Pad array to the specified length with a value

Description

array_pad(array $array, int $length, mixed $value): array

array_pad() returns a copy of the array padded to size specified by length with value value . If length is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of length is less than or equal to the length of the array then no padding takes place. It is possible to add at most 1048576 elements at a time.

Parameters

array

Initial array of values to pad.

length

New size of the array.

value

Value to pad if array is less than length .

Return Values

Returns a copy of the array padded to size specified by length with value value . If length is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of length is less than or equal to the length of the array then no padding takes place.

Examples

Example #1 array_pad() example

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?>

See Also

  • array_fill() - Fill an array with values
  • range() - Create an array containing a range of elements
Read article

PHP / array_pop — DevDocs

array_pop

(PHP 4, PHP 5, PHP 7, PHP 8)

array_pop Pop the element off the end of array

Description

array_pop(array &$array): mixed

array_pop() pops and returns the value of the last element of array , shortening the array by one element.

Note : This function will reset() the array pointer of the input array after use.

Parameters

array

The array to get the value from.

Return Values

Returns the value of the last element of array . If array is empty, null will be returned.

Examples

Example #1 array_pop() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

After this, $stack will have only 3 elements:

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

and raspberry will be assigned to $fruit .

See Also

  • array_push() - Push one or more elements onto the end of array
  • array_shift() - Shift an element off the beginning of array
  • array_unshift() - Prepend one or more elements to the beginning of an array
Read article

PHP / array_product — DevDocs

array_product

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_product Calculate the product of values in an array

Description

array_product(array $array): int|float

array_product() returns the product of values in an array.

Parameters

array

The array.

Return Values

Returns the product as an integer or float.

Examples

Example #1 array_product() examples

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";

?>

The above example will output:

product(a) = 384
product(array()) = 1
Read article