1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Side Effect in PHP

Discussion in 'HTML, Graphics & Programming' started by kohlditz, 3 Apr 2013.

  1. kohlditz

    Mobster

    Joined: 27 Sep 2005

    Posts: 4,354

    Location: London innit

    Try this.

    PHP:
    $x['foo'] = 'foo';
    $x['foo']['bar'] = 'bar';
    var_dump($x);
     
  2. fez

    Capodecina

    Joined: 22 Aug 2008

    Posts: 17,007

    Location: Tunbridge Wells

    Yeah, php is a pretty dirty language at times. It will try its best to cover for huge blunders but in doing so doesn't always come up with the correct answer. Have to admit though, that is a doozie.
     
  3. FragnaticDeath

    Gangster

    Joined: 20 Apr 2010

    Posts: 363

    Location: Kent, Canterbury

    PHP:
    $x['foo'][] = 'bar'
    $x['foo']['bar'] = 'bar';
    var_dump($x);
    hmmmm that is weird.... :/
     
    Last edited: 4 Apr 2013
  4. GravyMonster

    Capodecina

    Joined: 18 Oct 2002

    Posts: 14,566

    Location: The land of milk & beans

    For those of us who don't frequent the PHP world, what happens?

    My guess would be that it joins the array?

    *edit*
    Just tried it in an online editor. It's little like how in C# if you print an object to the screen you get the namespace of that object.
     
    Last edited: 4 Apr 2013
  5. namnoc

    Hitman

    Joined: 21 Dec 2005

    Posts: 575

    Location: Felixstowe

    It makes perfect sense.

    First you set set the element 'foo' to equal "foo"

    Then you try to set one character of that element. 'bar' isn't defined as as integer so is taken as 0 and the first character of "bar" is used as you are only setting one character.
     
  6. kohlditz

    Mobster

    Joined: 27 Sep 2005

    Posts: 4,354

    Location: London innit

    It makes sense once you realize what's going on, but it's messy.

    PHP:
    $x['foo'] = 'foo';
    As $x is uninitialized, the parser reads the [] as an array access and creates an $x as array of 'foo' => 'bar'

    PHP:
    $x['foo']['bar'] = 'bar';
    $x is now initialized as an array but $x['foo'] is a string within that array so the second set of brackets treated as (rarely) used string accessors. 'bar' is a string that is silently casted to 0 as that is what the string accessor expects and the value of the first character $x['foo'] is set to 'b' (as a range wasn't specified).

    It's an odd one, because you'd normally expect the code:

    PHP:
    $x['foo']['bar'] = 'bar';
    To set a $x -> child_element (foo) -> child_element (bar) to bar. The correct code is actually:

    PHP:
    $x = array('foo'=>'foo');
    $x['foo'] = array('bar'=>'bar');
    (The original value of $x['foo'] gets clobbered)