In PHP, we often need to generate HTML elements from arrays. For example, generating an option list for a <select> drop-down box, you usually use an array to dynamically fill the options of the drop-down box. The array_combine() function is a very practical tool that combines two arrays into an associative array to generate options for select drop-down boxes.
The array_combine() function accepts two arrays as parameters, the first array as the key to the new array, and the second array as the value of the new array. It returns a new associative array where each key-value pair consists of elements corresponding to two input arrays.
array_combine(array $keys, array $values): array
$keys : The key used to generate a new array.
$values : The value used to generate a new array.
If the number of elements in the two arrays is inconsistent, array_combine() throws a Warning error and does not return any value.
Suppose you have two arrays, one represents the option value for the drop-down box and the other represents the display text for the drop-down box. You can use array_combine() to combine these two arrays into an associative array and further use it to generate option elements of the select tag.
<?php
// Array of values for drop-down boxes
$values = ["1", "2", "3", "4", "5"];
// Display text array in drop-down box
$labels = ["One", "Two", "Three", "Four", "Five"];
// use array_combine Combine two arrays together
$options = array_combine($values, $labels);
// generate HTML Select Pull down box
echo '<select name="numbers">';
foreach ($options as $value => $label) {
echo '<option value="' . htmlspecialchars($value) . '">' . htmlspecialchars($label) . '</option>';
}
echo '</select>';
?>
Array definition : We define two arrays $values and $labels , which contain the value of the option and the display text respectively.
array_combine() merge array : combines two arrays into one associative array $options . Where each element of the $values array is used as the key to the associative array, and each element of the $labels array is used as the value.
Generate <select> tags : traverse the $options array through foreach loop and output HTML code for each option ( <option> ).
HTML security : Use the htmlspecialchars() function to ensure the output content is safe and prevent XSS attacks.
<select name="numbers">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
In this way, an automatic generation of a dynamic select drop-down box is achieved through array_combine() .
array_combine() is a very convenient function, especially when generating HTML elements, which allows you to quickly generate form elements such as drop-down boxes through simple array operations. When using it, just by ensuring that the number of elements in the two arrays is consistent, you can successfully merge into an associative array to generate the required HTML content.