- sprintf: documentation ( source)
- printf: documentation ( source)
<?php
function esc_attr( $string ) {
return $string;
}
function sanitize_key( $key ) {
return $key;
}
function test( $choices ) {
foreach( $choices as $key => $value ) {
if ( is_integer( $key ) ) {
$field_name = "field[$key]";
} elseif ( is_string( $key ) ) {
$field_name = sprintf( 'field[%s]', sanitize_key( $key ) );
} else {
// may want to throw an error here.
}
printf(
'<input name="%s" value="1"/>',
esc_attr( $field_name )
);
echo "\n";
}
}
echo "An indexed array\n";
$choices = array( 'Red', 'Blue', 'Green' );
test( $choices );
echo "\n\nAssociative array\n";
$choices = array( 'red' => 'Red', 'blue' => 'Blue', 'green' => 'Green' );
test( $choices );