Could anyone let me know how can I allow duplicate keys in php array? I have already read all identical posts concerning this questions and it does not answer my question.
In the following example, I want to pass the second 'separator' key without rename it.
$data = [
'username' => array(
'type' => 'checkbox',
'id' => 'username',
'label' => 'Show Username Field',
'default' => true,
),
'separator' => array(
'type' => 'separator',
'height' => 'thin'
),
'heading' => array(
'type' => 'textarea',
'id' => 'heading',
'label' => 'Heading Text',
'default' => '',
),
'separator' => array(
'type' => 'separator',
'height' => 'thin'
),
'placeholder' => array(
'type' => 'text',
'id' => 'placeholder',
'label' => 'Placeholder Text',
'default' => 'Your name',
),
];
echo '<pre>';
print_r($data);
echo '</pre>';
That cannot be done in the way you are trying to do it. The array key is what identifies the entry in the array. You can only have one element with the same key. So in your example your second element with the separator key is overwriting the first element.
So you have to solve it in some other way. One way would be to not use explicit keys and just us numeric indexes. You already have your key value as the id field in each of your array entries.
That would look something like this:
$data = [
array(
'type' => 'checkbox',
'id' => 'username',
'label' => 'Show Username Field',
'default' => true,
),
array(
'type' => 'separator',
'height' => 'thin'
),
array(
'type' => 'textarea',
'id' => 'heading',
'label' => 'Heading Text',
'default' => '',
),
array(
'type' => 'separator',
'height' => 'thin'
),
array(
'type' => 'text',
'id' => 'placeholder',
'label' => 'Placeholder Text',
'default' => 'Your name',
),
];
echo '<pre>';
print_r($data);
echo '</pre>';
You would have to loop through the entries to find a specific element. But if you are generating html from the data, I guess you are looping through it anyway.