dmcoding dmcoding - 5 months ago 10
PHP Question

Array updating temporarily, but not updating permanently in PHP

Here's the code:

if($condition == 'condition1' || $condition == 'condition2')
{
$found = false;
//loop through the array of customers contracts
foreach($cust_cont as $cust)
{
//if the customer is found
if ($cust["customer"] == $customer)
{
$temp = floatval($cust["hoursThisPer"]);
$temp += $time;
$cust["hoursThisPer"] = $temp;
$found = true;
}
}
if ($found == false)
{
$cust_cont[] = array("customer" => "$customer", "hoursUsed" => $hoursUsed,
"hoursAvail" => $allowed, "hoursThisPer" => (0 + $time));
}
}


So, what I'm trying to get this to do is traverse an array. If the array does have an entry for a customer, I want to add time to that customer's used time. If there is not an entry for the customer, I want to create an entry for that customer in my array and initialize it's values.

The array's entries are getting initialized properly, but when I try to update them, something funky is happening. For example, if I have customer1 in the array and I want to add to customer1's hoursThisPer, it goes through the motions of adding to that spot. However, the next time it needs to update, customer1's hoursThisPer is set to the initial value as opposed to the updated value. I can't figure out the flaw in my logic. Help would be greatly appreciated. I have some sample output.

Customer1:0.25

time: 0.25

temp: 0.5

0.5

Customer1:0.25

time: 1.50

temp: 1.75

1.75

Customer1:0.25

time: 0.50

temp: 0.75

0.75


The format is Customer: initial time; time to add; the expected total of initial time + added time; the array's value after being "updated"; the next instance of the customer being found (and the cycle continues).

Answer

You need to fetch your array by reference, otherwise you're just updating a new variable called $cust:

if($condition == 'condition1' || $condition == 'condition2')
{   
    $found = false;
    //loop through the array of customers contracts
    foreach($cust_cont as &$cust)
    {   
        //if the customer is found
        if ($cust["customer"] == $customer) 
        {
            $temp = floatval($cust["hoursThisPer"]);
            $temp += $time;
            $cust["hoursThisPer"] = $temp;
            $found = true;
        }
    }
    if ($found == false)
    {
        $cust_cont[] = array("customer" => "$customer", "hoursUsed" => $hoursUsed, 
           "hoursAvail" => $allowed, "hoursThisPer" => (0 + $time));
    }
}

Here I added a & before $cust declaration in the foreach loop. With this $cust is not a new variable with the value of the current $cust_cont element but an actual reference to this element.