Skip to content

Instantly share code, notes, and snippets.

@castroalves
Last active March 11, 2020 16:32
Show Gist options
  • Save castroalves/6688ceb69125e86f3e29c45dda9d9294 to your computer and use it in GitHub Desktop.
Save castroalves/6688ceb69125e86f3e29c45dda9d9294 to your computer and use it in GitHub Desktop.
Small experiment using anonymous functions in arrays
<?php
$form = [
'action' => 'http://nextbike.com',
'target' => '_blank',
'method' => 'POST',
'fields' => [
['type' => 'text', 'name' => 'first_name', 'label' => 'First Name'],
['type' => 'text', 'name' => 'last_name', 'label' => 'Last Name'],
['type' => 'date', 'name' => 'birthday', 'label' => 'Birthday'],
['type' => 'submit', 'name' => 'submit', 'label' => 'Sign Up!'],
]
];
$html = [
'open' => function($form) {
return '<form action="'.$form['action'].'" method="'.$form['method'].'" target="'.$form['target'].'">' . PHP_EOL;
},
'fields' => function($fields) {
$htmlFields = '';
foreach($fields as $field) {
$htmlFields .= '<p>' . PHP_EOL;
if($field['type'] !== 'submit') {
$htmlFields .= '<label for="'.$field['name'].'">'.$field['label'].'</label>' . PHP_EOL;
$htmlFields .= '<input type="'.$field['type'].'" name="'.$field['name'].'" id="'.$field['name'].'" />' . PHP_EOL;
} else {
$htmlFields .= '<input type="'.$field['type'].'" value="'.$field['label'].'" name="'.$field['name'].'" id="'.$field['name'].'" />' . PHP_EOL;
}
$htmlFields .= '</p>' . PHP_EOL;
}
return $htmlFields;
},
'close' => '</form>' . PHP_EOL,
];
echo $html['open']($form);
echo $html['fields']($form['fields']);
echo $html['close'];
// Outputs:
// <form action="http://nextbike.com" method="POST" target="_blank">
// <p>
// <label for="first_name">First Name</label>
// <input type="text" name="first_name" id="first_name" />
// </p>
// <p>
// <label for="last_name">Last Name</label>
// <input type="text" name="last_name" id="last_name" />
// </p>
// <p>
// <label for="birthday">Birthday</label>
// <input type="date" name="birthday" id="birthday" />
// </p>
// <p>
// <input type="submit" value="Sign Up!" name="submit" id="submit" />
// </p>
// </form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment