$input1=array('One','Two','Three','Four','Five');
$input2=array(1,2,3,4,5);
$output=array_combine($input1,$input2);
print_r($output);
Output is here
Array ( [One] => 1 [Two] => 2 [Three] => 3 [Four] => 4 [Five] => 5 )
Syntax
array_combine ($input_array1 ,$input_array2 )
| Parameter | DESCRIPTION |
|---|---|
| $input_array1 | Required : Input array of which kyes will be retained. |
| $input_array2 | Required : Input array of which values will be retained. |
<?php
$keys = ['name', 'email'];
$values = ['John Doe', 'john@example.com', 25]; // Extra value
// This will trigger a warning because the arrays are not of equal length
$result = @array_combine($keys, $values);
if ($result === false) {
echo "Error: Arrays must have the same length!";
} else {
print_r($result);
}
?>
Output
Error: Arrays must have the same length!
<?php
$labels = ['Name', 'Email', 'Age'];
$userInput = ['Alice', 'alice@example.com', 28];
// Combining form labels with user input
$formData = array_combine($labels, $userInput);
print_r($formData);
?>
Output
Array
(
[Name] => Alice
[Email] => alice@example.com
[Age] => 28
)
<?php
$keys = ['Name', 'Email'];
$values = ['Bob', null]; // Null value in the array
$combined = array_combine($keys, $values);
// Check for null values
foreach ($combined as $key => $value) {
if (is_null($value)) {
echo "$key has no value set.<br>";
} else {
echo "$key: $value<br>";
}
}
?>
Output
Name: Bob
Email has no value set.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.