Doubt on locating array element

Asked

Viewed 32 times

-2

I made this program in php. The answer should be "20", but it informs :

Undefined index: cod_produto in [...][...] on line 21</

for($i =0; $i < 20; $i++){  
      $valores[] = array (

    $i => 
    array(
        'cod_produto' => $i,
        'valor' => $i*2
    ));

};



$codProcura = 10;
$valor1 = 0;

for($x = 0; $x < 20; $x++){    
    $search = $valores[$x];
    if($valores[$x]['cod_produto'] == $codProcura){///esta eh a linha 21
        $valor1 = $search['valor'];
        break;
    }
}
echo $valor1;

1 answer

1

There is a problem at the moment that you are building the array. At this point, you create a new index in the array $valores and, to it, assigns an array. This array, in turn, contains a single index $i which contains another array containing the information.

Decrease to 3 the upper limit, see the result.

for($i =0; $i < 3; $i++){
    $valores[] = array(
        $i => 
            array(
                'cod_produto' => $i,
                'valor' => $i*2
            )
    );
};

echo "<pre>"; var_dump($valores); echo "</pre>";

Upshot:

array(3) {
  [0]=>
  array(1) {
    [0]=>
    array(2) {
      ["cod_produto"]=>
      int(0)
      ["valor"]=>
      int(0)
    }
  }
  [1]=>
  array(1) {
    [1]=>
    array(2) {
      ["cod_produto"]=>
      int(1)
      ["valor"]=>
      int(2)
    }
  }
  [2]=>
  array(1) {
    [2]=>
    array(2) {
      ["cod_produto"]=>
      int(2)
      ["valor"]=>
      int(4)
    }
  }
}

In fact, $valores[$x] has another index array $x, and this yes, in turn, has the content.


I suggest you change the code to the next one and get what you want:

for ($i =0; $i < 20; $i++) {
    $valores[] = array( // Cria um novo índice e adiciona.
    // $valores[$i] = array( // Esta é outra opção (equivalente)
        'cod_produto' => $i,
        'valor' => $i*2
    );
};

$codProcura = 10;
$valor1 = 0;

for ($x = 0; $x < 20; $x++) {
    $search = $valores[$x];
    if ($valores[$x]['cod_produto'] == $codProcura) {
        $valor1 = $search['valor'];
        break;
    }
}

echo $valor1;
  • very good, it was a lapse that I had not understood, I thank immensely.

  • @Silezia, if the answer solved your problem and there was no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.