inside Habbie's mind

it's shit like this, PHP

written by peter, on Aug 20, 2011 7:47:00 AM.

This post has two snippets of code that demonstrate some aspects of the braindeadness that appears to be inherent in PHP arrays. I suggest trying to predict the output (especially with exhibit A) before you run the scripts, for extra fun ;) Exhibit A:
<?php
        // create empty array $a
	$a = array();
        // append two items to it
	$a[] = "a";
	$a[] = "b";
        // remove last item using array_pop
	array_pop($a);
        // append another item
	$a[] = "c";

	$b = array();
	$b[] = "a";
	$b[] = "b";
        // remove last item using unset
	unset($b[1]);
	$b[] = "c";
        // print key for value "c"
	print array_search("c", $a). "\n";
	print array_search("c", $b). "\n";
?>
This behaviour does not clearly follow from the docs.

Exhibit B:

<?php
        // create pre-filled key-less array $a
	$a=array('a','b');
        // dump it
	print_r($a);
        // json-dump it
	print json_encode($a)."\n";
        // add key/value item to array
	$a['x']='c';
	print_r($a);
	print json_encode($a)."\n";
?>
This behaviour is described in examples in the docs. It demonstrates how braindead the PHP array type is.

(I’m on PHP 5.3.4).

Comments

  • For those of us not intimately in love with php, wtf do those snippets do?

    Comment by Sybren — Aug 20, 2011 8:46:50 AM | # - re

  • I have added some code comments, and an introduction. Is this helpful?

    Comment by peter — Aug 20, 2011 9:56:04 AM | # - re

  • Exhibit A, The only thing not in the docs is that array_pop re-indexes an array.

    Comment by phx — Jan 19, 2012 11:37:01 AM | # - re

Leave a Reply