array_combine()
21st January 2021
0 Comments
Programming Language
PHP [Versions: 5, 7, 8]
Syntax
Typical Usage
array_combine() is used to combine two arrays laterally. ie. one array’s values are used as keys and the other’s values are used as values.
Accepted Parameters
- keys (array) (Required): The array you wish to use as keys.
- values (array) (Required): The array you wish to use as values.
Notes
Both arrays must have the same amount of elements otherwise an error will be thrown.
Do not confuse array_combine() with array_merge(). array_combine() combines two arrays using one as keys and the other as values while array_merge() concatenates two arrays.
Examples
Example 1
<?php
$keys = ['firstname', 'lastname', 'age'];
$values = ['anthony', 'stark', 55]
$ironman_info = array_combine($keys , $values);
print_r($ironman_info);
The above will output:
Array ( [firstname] => anthony [lastname] => stark [age] => 55 )
Used In Projects
Was This Helpful?
If this post has helped you, please let me know. Your feedback will be highly appreciated and will help me build better content.