Skip to content

Instantly share code, notes, and snippets.

@attilammagyar
Created April 18, 2012 22:12
Show Gist options
  • Save attilammagyar/2416993 to your computer and use it in GitHub Desktop.
Save attilammagyar/2416993 to your computer and use it in GitHub Desktop.
My favorite PHP gotchas
<?php
// https://bugs.php.net/bug.php?id=53567
function create_pdo()
{
return new PDO("mysql:host=localhost;dbname=test",
"test", "my_password",
array(PDO::ATTR_PERSISTENT => true));
}
$pdo1 = create_pdo();
$pdo2 = create_pdo();
$pdo1->query("SELECT i_can_has_fail() ;");
var_dump($pdo2->errorInfo());
?>
<?php
function dump($var)
{
return str_replace("\n", "", var_export($var, true));
}
echo "Sorting a mixed type array (manual does warn about issues):\n\n";
$array = array("1", 1, "a");
echo " Unsorted array: " . dump($array) . "\n";
sort($array);
echo " After sorting: " . dump($array) . "\n";
sort($array);
echo " Sorting again: " . dump($array) . "\n";
echo "\nSorting a non-mixed type array (should be safe):\n\n";
$array = array("a", "2", "3e-1");
echo " Unsorted array: " . dump($array) . "\n";
sort($array);
echo " \"Regular\" sorting: " . dump($array) . "\n";
sort($array, SORT_NUMERIC);
echo " Numerical: " . dump($array) . "\n";
sort($array, SORT_STRING);
echo " As strings: " . dump($array) . "\n";
?>
<?php
function print_equality($a, $b)
{
$repr_a = var_export($a, true);
$repr_b = var_export($b, true);
echo "$repr_a == $repr_b is ";
var_dump($a == $b);
}
print_equality("42", "042");
print_equality("4.2e1", "042");
print_equality("0xE", "0Xe");
print_equality("0E999", "42e-4242");
?>
<?php
error_reporting(E_ALL);
function print_strpos($haystack, $needle)
{
$repr_haystack = var_export($haystack, true);
$repr_needle = var_export($needle, true);
echo "Find needle=$repr_needle in haystack=$repr_haystack: ";
var_dump(strpos($haystack, $needle));
}
print_strpos("hello", "hell");
print_strpos("", "world");
print_strpos(false, null);
print_strpos("world", "");
print_strpos("", "");
?>
<?php
var_dump(substr("hello", 0, 0));
var_dump(substr("", 0, 0));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment