it's shit like this, PHP

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).

blogroll

social