Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP - Updating arrays within arrays using foreach

Options
  • 12-05-2011 12:05am
    #1
    Registered Users Posts: 1,127 ✭✭✭


    Hey guys.

    Ok, been googling for a little while now, but Im having no joy. Consider the following pseudo code.
    $a = array();
    $b = array("foo" => "bar", "blah" => "two", "what" => "yeah");
    $a[] = $b; 
    
    // so far so good.. however
    
    foreach($a as $x){
       // First array item is obviously $b
       if($someBoolean){
         $x['hasValue'] = true;
       }
    }
    

    But $b is never updated with the new element.

    Any thoughts?


Comments

  • Registered Users Posts: 8,488 ✭✭✭Goodshape


    Array's aren't persistent like that. When you foreach $a as $x, $x is a new thing... it has the properties of $b but it isn't $b. Also, on the next iteration of the loop it's going to be re-written anyway ($x is set for each value in $a). Changes you make to $x do not carry back.

    Depending on your script though, you should be able to rework it. For your psudo-code, something like:

    [php]
    $a = array();
    $b = array("foo" => "bar", "blah" => "two", "what" => "yeah");
    $a[] = $b; // so now $a[0] is $b;

    $i = 0;
    foreach($a as $x)
    {
    if($someBoolean)
    {
    $a[$i] = true; // now we're changing the $a[0] variable, not the $x.
    }
    $i++;
    }
    [/php]


  • Registered Users Posts: 3,140 ✭✭✭ocallagh


    or if the array is associative you don't need the counter

    [PHP]foreach($array as $key=>$value)
    {
    $array[$key] = $newvalue;
    }[/PHP]


  • Registered Users Posts: 1,657 ✭✭✭komodosp


    I believe you can update it using a reference to the element... i.e.
    foreach ($array as &$element) {
     $element = $new_value;
    }
    


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    foreach ($array as $k=>$v) {
       $array[$k]=$newValue;
    }
    


  • Closed Accounts Posts: 10 Skiex


    Your using a hasValue.

    Are you just checking if a variable is in an array?

    Whats the goal?


  • Advertisement
Advertisement