PHP array_combine method example

124 views 4 months ago PHP

In this tutorial article, we have PHP array_combine method with example. Suppose we have two array and we want to create one array i.e, one array use for key and one array for value.

This method is used with other methods when you want to work with array and analyze data.

<?php
$colors = array('red', 'orange', 'yellow');
$fruits = array('apple', 'mango', 'pineapple');
$fruit_colors = array_combine($colors, $fruits);
print_r($fruit_colors);
// Array ( [red] => apple [orange] => mango [yellow] => pineapple )

The method returns false if the number if items not same in both array. If two keys are the same, the first item will be override with second one.

<?php
$colors = array('red', 'orange', 'red', 'yellow');
$fruits = array('apple', 'mango', 'berry', 'pineapple');
$fruit_colors = array_combine($colors, $fruits);
print_r($fruit_colors);
// Array ( [red] => berry [orange] => mango [yellow] => pineapple )

I hope you liked this article and it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]