0

My problem is, i have a 2D Array and i want to override the value of an element that was set.

My code is as follows:

$indes="-1";
$inupccode="-1";
$inuomcode="-1";
$instdpack="-1";
$inweight="-1";
$inlength="-1";
$inwidth="-1";
$inheight="-1";
$inunitprice="-1";
$infamcode="-1";

$basicInfo = array(array($indes,"prdes1_35", $inupccode,
                        "prupc#_2", $inuomcode,"prwuts_3-1",
                        $instdpack,"prwuns_12", $inweight,
                        "prgrwt_11", $inlength,"prlong_7",
                         $inwidth,"prwide_7", $inheight,"prhigh_7", 
                         $inunitprice,"prprce_12", $infamcode,"proga2"));
echo "before";
print_r($basicInfo); 

foreach($basicInfo as $value){
    foreach ($value as $id){
        if($id == "prdes1_35"){
            $value = 2;
        }
    }
}
echo "after";
print_r($basicInfo); 

In the code for the value of $indes i would like to change from -1 to 2 and the reminder array value must remain as "-1". How can i achieve this?

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
John Public
  • 33
  • 2
  • 5

1 Answers1

0

Biggest problem first: I dont think your code does what you intent to achieve. Are you sure you understand (multi dimensional) arrays?

The other issue is the way you try to change $value. Please check this post:

(https://stackoverflow.com/questions/15024616/php-foreach-change-original-array-values)

for information on how to change an array you run through with foreach.

Simplest solution for you would be:

foreach($basicInfo as &$value){
    foreach ($value as $id){
        if($id == "prdes1_35"){
            $value = 2;
        }
    }
}

Mind the ampersand (&) before the $value variable. The referenced post an the link in there hold all the explanation necessary to understand what it means.

Perfomancewise this would be the best solution, especially when your array gets big:

foreach($basicInfo as $key => $value){
        foreach ($value as $id){
            if($id == "prdes1_35"){
                $basicInfo[$key][$value] = 2;
            }
        }
    }

NOTE: I did not change your codes logic (that is broken, I assume). I just demonstrated how to change a value when iterating through an array with foreach.

Community
  • 1
  • 1
Stefan Dochow
  • 1,454
  • 1
  • 10
  • 11