Skip to content

Instantly share code, notes, and snippets.

@BjornW
Last active January 25, 2017 09:52
Show Gist options
  • Save BjornW/69c18525137f2ad86c4557009f9bbde8 to your computer and use it in GitHub Desktop.
Save BjornW/69c18525137f2ad86c4557009f9bbde8 to your computer and use it in GitHub Desktop.
When using array's with a switch make sure alle keys in the array are strings or else you'll get weird issues. I'd rather have PHP give me an error instead of casting!?
<?php
// Weird things can happen with an array having both strings and integers as
// keys...
// First we create a test array with only strings as keys
$strings_array = array( 'foo' => 1, 'bar' => 2);
// Second, using the strings array we create a new array and add a key with an integer zero
$strings_and_int_array = $strings_array;
$strings_and_int_array[0] = 666;
// Loop through the array and use a switch statement which based on the key prints a value
function looper( $array ) {
foreach( $array as $key => $val ) {
switch( $key ) {
case 'foo':
echo "Case = foo and the value is $val" . PHP_EOL;
break;
case 'bar':
echo "Case = bar and the value is $val" . PHP_EOL;
break;
}
}
}
echo 'Loop over the Strings array' . PHP_EOL;
looper( $strings_array);
echo '------------------------------------------' . PHP_EOL;
echo 'Loop over the Strings and Integers array'. PHP_EOL;
looper( $strings_and_int_array);
echo 'So why does foo print twice?' . PHP_EOL;
echo "My assumption is PHP casts the String 'foo' to an Integer and thus it will be zero" . PHP_EOL;
$foo_int = intval('foo');
echo 'The result of $foo_int = intval(\'foo\'); is ' . $foo_int . PHP_EOL;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment