Jump to content

Help with array issue


EchoFool

Recommended Posts

Hey

 

I have an array comparison which returns values in an array but then i need to change values that are 1 in the array to 14 so currently i use a loop but i get undefined offset issues.

 

 

How can i change it to work properly with error? This is my current attempt:

 

 $HC = array_diff($Values,$Temp);    
        $i = 0;
        foreach($HC as $value) {
           if($HC[$i] == 1) {
           $HC[$i] = 14;
           }
           $i++;
        }    

Link to comment
https://forums.phpfreaks.com/topic/217621-help-with-array-issue/
Share on other sites

And I am pretty sure array_diff() is not the correct function to use on your array. Assuming you have 2 arrays and you want to find the differences in them, arg1, arg2 in that function.. array_diff would output anything that is in arg1 that does not exist in arg2 - arg 1 and 2 being arrays of course...

if array undefined offset is the issue you can use isset

 

$HC = array_diff($Values,$Temp);    
        $i = 0;
        foreach($HC as $value) {
           if(isset($HC[$i]) && $HC[$i] == 1) {
           $HC[$i] = 14;
           }
           $i++;
        }    

if array undefined offset is the issue you can use isset

 

$HC = array_diff($Values,$Temp);    
        $i = 0;
        foreach($HC as $value) {
           if(isset($HC[$i]) && $HC[$i] == 1) {
           $HC[$i] = 14;
           }
           $i++;
        }    

 

 

I thought of using this but thought - surely the for loop wouldn't loop if it was not set anyway because it only loops whilst it is set no ?

You are getting undefined offsets because they dont exist in the array.. use the key of the array like so..

$HC = array_diff($Values,$Temp); 
foreach($HC as $key=>$value) {
           if($value == 1) {
           $HC[$key] = 14;
           }
        }

You are getting undefined offsets because they dont exist in the array.. use the key of the array like so..

$HC = array_diff($Values,$Temp); 
foreach($HC as $key=>$value) {
           if($value == 1) {
           $HC[$key] = 14;
           }
        }

 

Yes, or you can change it directly using a reference:

 

foreach($HC as &$value) {
if($value == 1) $value = 14;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.