Arrays with keys that vary numerically

Asked

Viewed 65 times

2

In the PHP I’m declaring my variable like this:

$id_produto = $dados["id_produto".$input.""];

Where $inc is increment within the loop and the $dados["id_produto".$input.""] should return something like $dados["id_produto1"], $dados["id_produto2"] ...

It is correct to declare the variable this way?

  • wrong would be a strong word... But I think you could generate a multidimensional array. So: $produtos[0]["id_produto"] = 1 ... $produtos[0]["nome"] = "panela"... $produtos[1]["id_produto"] = 2 ... $produtos[1]["nome"] = "prato"

  • But it all depends on what you intend to do...

  • so... is that in my application I have several inputs with the id: id_productN... and I will take the value of each id of these and play inside a while, so would have something like $id_product = $data["id_product". $input."];

  • that $id_product = $data["id_product". $input." ]; would have to return me something like: $id_product = id_product1 <== relating to the value of input 1 and so on

1 answer

3


This is wrong, or at least it’s gambiarra, if it has another dimension of data, then it should create this dimension, something like:

$dados["id_produto"][$input];

I put in the Github for future reference.

Note that only the element identified by "id_produto" would have that additional dimension.

It’s not that I can’t do it at all, but it’s the wrong programming mechanism. It would be only half wrong, or maybe right, if the final index was never used as a variable.

  • Thank you! That -> $data["id_product"][$input]; -> would be right? Isn’t that usual? The right thing would be for me to already pass the id_prodoN already 'ready', of an input, span, etc.?

  • 2

    @Nosredna does not... The "right", or the "right" would be to do something similar as Maniero suggested. The way you ask the question is that it is not the usual.

  • 1

    @Nosredna I don’t say it’s wrong, because you may have a good reason to do it this way, although I can’t see it in your question.

  • @Andrei Rabbit Thank you! my application is similar to the link: https://answall.com/questions/363811/addir-ou-remover-inputs-com-js/363855?noredirect=1#comment726430_363855 to be passed for validation. It turns out that besides these inputs id_nome1, id_nome2, id_nomeN I still have id_idade1, id_idadeN and not to put all inside Hidden I tried this other alternative.

Browser other questions tagged

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