Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Problem with foreach loop for updating array element

    • 0
    • 2
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 215
    Comment on it

    If we are traversing an array and need to update an element in some condition then it is quite tricky to do that in foreach loop.

    For example, if we need to increase each element by 2 of an integer array then we can do that using for loop in this way:

    $count = count($my_array);
    for ($i = 0; $i < $count; $i++) {
      $my_array[$i] += 2;
    }
    

    But it is not possible to do this in foreach loop:

    foreach ($my_array as $data) {
      $data += 2;
    }
    

    because in this way foreach is being used "by-value" so we can not update original element. To do that we have to use foreach loop in this way:

    foreach ($my_array as &$data) {
      $data += 2;
    }
    

    or

    foreach ($my_array as $key=>$val) {
      $my_array[$key] += 2;
    }
    

    Hope this will help someone.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: