Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
array
communitycreator

What is the array_combine method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The array_combine method in PHP takes two arrays as input and returns a new array with the keys taken from the first array and the values taken from the second array.

Syntax

array_combine(array $keys_array, array $values_array): array

Parameters

  • keys_array: The values of this array will be used for keys of the returning array.

  • values_array: The values of this array will be used for values of the returning array.

Both parameters should have an equal number of elements, otherwise array_combine will throw a warning.

Code

Example 1

<?php
$key_array = array('one', 'two', 'three');
$values_array = array(1, 2, 3);
$new_array = array_combine($key_array, $values_array);
print_r($new_array);
?>

Explanation

In the code above, we create two arrays.

$key_array = array('one', 'two', 'three');
$values_array = array(1, 2, 3);

We call the array_combine method.

array_combine($key_array, $values_array);

This will take keys from the key_array and values from the values_array, and combine them as a new array, which is then returned.

Example 2

<?php
$key_array = array('A', 'A', 'A');
$values_array = array(1, 2, 3);
$new_array = array_combine($key_array, $values_array);
print_r($new_array);
?>

Explanation

In the code above, the values of keys_array are the same (all the values are A). So, the array returned by the array_combine method will contain one element with the last updated value (3) for the A key.

Please refer here to handle this case.

RELATED TAGS

php
array
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring