Results 1 to 2 of 2

Thread: add to existing array

  1. #1
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default add to existing array

    i am adding to an existing array and it seems to work like this
    Code:
    $arr[] .= 'a';
    $arr[] .= 'b';
    $arr[] .= 'c';
    but if i wanted it written in 1 line like this, what is the correct way?
    this doesnt seem to work
    Code:
    $arr[] .= array('a', 'b', 'c');
    re:
    array_push seems to work
    Code:
    array_push($arr, 'a', 'b', 'c', 'd');
    Last edited by ggalan; 05-17-2012 at 08:56 PM.

  2. #2
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default

    Quote Originally Posted by ggalan View Post
    i am adding to an existing array and it seems to work like this
    Code:
    $arr[] .= 'a';
    $arr[] .= 'b';
    $arr[] .= 'c';
    but if i wanted it written in 1 line like this, what is the correct way?
    this doesnt seem to work
    First: you shouldn't be using the concatenation assignment ( .= ).
    Once that's corrected, both methods will work, but will provide different results:
    PHP Code:
    <?php
    $array1
    [] = 'a';
    $array1[] = 'b';
    $array1[] = 'c';
    var_dump$array1 );
    /* output:
    array(3) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "b"
      [2]=>
      string(1) "c"
    }
    BTW, this:
        $arr = array();
        array_push($arr, 'a','b','c' );
    has _exactly_ the same result as the method above (but is less efficient)
    */

    $array2[] = array( 'a','b','c' );
    var_dump$array2 );
    /* output:
    array(1) {
      [0]=>
      array(3) {
        [0]=>
        string(1) "a"
        [1]=>
        string(1) "b"
        [2]=>
        string(1) "c"
      }
    }
    */
    I suspect what you want, however, is a simple array construct:
    PHP Code:
    <?php
    $array 
    = array( 'a','b','c' );
    var_dump$array );
    /* output:
    array(3) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "b"
      [2]=>
      string(1) "c"
    }
    */

  3. The Following User Says Thank You to traq For This Useful Post:

    ggalan (05-31-2012)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •