Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

PHP - Updating arrays within arrays using foreach

  • 12-05-2011 12:05AM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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, Registered Users 2 Posts: 3,141 ✭✭✭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, Registered Users 2 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