setting values in associative array to 0

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • R. Rajesh Jeba Anbiah

    #16
    Re: setting values in associative array to 0

    Ewoud Dronkert wrote:[color=blue]
    > On 6 Jun 2005 06:49:37 -0700, pauld wrote:[color=green]
    > > help please ?[/color]
    >
    > Tested and working:
    >
    > $a = array( 'one' => 1, 'two' => 2, 'three' => 3 );
    >
    > // solution 1
    > $b = $a;
    > foreach ( $b as $k => $v ) $b[$k] = 0;[/color]
    <snip>

    IIRC, this is highly discouraged solution. Better use each().

    --
    <?php echo 'Just another PHP saint'; ?>
    Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com

    Comment

    • Ewoud Dronkert

      #17
      Re: setting values in associative array to 0

      On 8 Jun 2005 08:54:35 -0700, R. Rajesh Jeba Anbiah wrote:[color=blue][color=green]
      >> foreach ( $b as $k => $v ) { ... }[/color]
      >
      > IIRC, this is highly discouraged solution. Better use each().[/color]

      Per the manual, it is functionally identical to

      reset( $b );
      while ( list( $k, $v ) = each( $b ) ) { ... }

      So certainly not "highly discouraged".


      --
      Firefox Web Browser - Rediscover the web - http://getffox.com/
      Thunderbird E-mail and Newsgroups - http://gettbird.com/

      Comment

      • R. Rajesh Jeba Anbiah

        #18
        Re: setting values in associative array to 0

        Ewoud Dronkert wrote:[color=blue]
        > On 8 Jun 2005 08:54:35 -0700, R. Rajesh Jeba Anbiah wrote:[color=green][color=darkred]
        > >> foreach ( $b as $k => $v ) { ... }[/color]
        > >
        > > IIRC, this is highly discouraged solution. Better use each().[/color]
        >
        > Per the manual, it is functionally identical to
        >
        > reset( $b );
        > while ( list( $k, $v ) = each( $b ) ) { ... }
        >
        > So certainly not "highly discouraged".[/color]

        IMHO, you're quoting the manual wrongly. When you have to modify the
        array, foreach is highly discouraged because of it's behavior (as
        explained in manual).

        --
        <?php echo 'Just another PHP saint'; ?>
        Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com

        Comment

        • Chung Leong

          #19
          Re: setting values in associative array to 0

          Inefficient? maybe. Highly discouraged? I don't think so.

          Haven't benchmarked this, but array_walk() is probably the most
          efficient way of modifying elements in an array, with the function
          hopping from element to element using the internal linked list instead
          of performing a hash lookup for each. Of course, the difference is
          likely to be so small that it barely registers.

          Comment

          Working...