3v4l.org

run code in 300+ PHP versions simultaneously
<?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 );
Output for 7.3.13 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
An indexed array <input name="field[0]" value="1"/> <input name="field[1]" value="1"/> <input name="field[2]" value="1"/> Associative array <input name="field[red]" value="1"/> <input name="field[blue]" value="1"/> <input name="field[green]" value="1"/>
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 An indexed array <input name="field[0]" value="1"/> <input name="field[1]" value="1"/> <input name="field[2]" value="1"/> Associative array <input name="field[red]" value="1"/> <input name="field[blue]" value="1"/> <input name="field[green]" value="1"/>

preferences:
151.3 ms | 402 KiB | 143 Q