array_combine(): keys of one array and values of another

$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 )
ParameterDESCRIPTION
$input_array1Required : Input array of which kyes will be retained.
$input_array2Required : Input array of which values will be retained.
Returns an array with keys of first array and values of second array.

Returns FALSE if both arrays are not having equal number of elements.

Example 1: Handling Mismatched Array Lengths

<?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!

Example 2: Real-World Use Case - Combining Form Labels and User Input

<?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
)

Example 3: Handling NULL values in Combined Arrays

<?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.

Array REFERENCE Getting keys of an array
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer