Get values from an array separately

Asked

Viewed 165 times

1

I have a page where shows me text fields to be filled (inputs), containing a "+" in it, in case the user needs more forms to fill in..

The input code of the form that receives the values entered by the user is thus:

Nome completo:<input name="nomeCompleto[]" id="nomeCompleto" type="text">

Taking into account that the "nomeCompleto[]" is referring to an array, so I made my PHP code receive the values through the $_POST, in such a way:

if(isset($_POST['nomeCompleto'])){
foreach($_POST["nomeCompleto"] as $nameC)
    {
        echo " => " . $nameC . "<BR>";

    }

Thus the above code returns me such values:

=> João
=> Fernando
=> Jacinto Ades Graça Vindo
=> Lucas
Array ( [0] => João [1] => Fernando [2] => Jacinto Ades Graça Vindo [3] => Lucas )   

The values with "=>" are the values that were typed in the inputs by the user, with php I made those values passed to an array, so they are sorted and identified in such a way. And with the "count" php, I can count how many items my array has, so it prints the value on the screen "4", why there are 4 values(from 0 to 3).

The complete code that returns me the values typed above was this way:

if(isset($_POST['nomeCompleto'])){
foreach($_POST["nomeCompleto"] as $nameC)
    {
        echo " => " . $nameC . "<BR>";

    }
        ?><br /><?php
        print_r(($_POST["nomeCompleto"]));// aqui ele me retorna os valores do array e suas respectivas posições( [0] => João [1] => Fernando...)
        ?><br /><?php

        $count = count($_POST["nomeCompleto"]); // aqui ele realiza a contagem do array via $_POST
        printf($count); // aqui ele me retorna o valor "4" que é a quantidade de 'itens' que compõe meu array.
        ?><br /><?php
        print_r($nameC); /*coloquei esse print_r pra ver o que ele me retornaria apenas com a variável $nameC.. e aqui ele me retorna apenas o ultimo valor do array, que seria "Lucas", cá esta um erro */
        ?><br /><?php

}

The first question is:

In "echo " => " . $nameC . "<BR>";" it returns me the values of the variable $nameC in such a way:

=> João
=> Fernando
=> Jacinto Ades Graça Vindo
=> Lucas

But why when I give one "print_r($nameC);" he returns only "Lucas"? and not all other names. (regardless if it is printf or print_r or echo)

The question is, how can I get such values separately within a loop? Following such logic in the case:

while($i=0;$i<$count;$i++){

printf($nameC[$i]);

}

Obs.: the variable "$nameC" is the variable I set up to be able to allocate the array values (in which case the array comes from a web page, using the $_POST i pulled the values and assign such to that variable

Note: It necessarily needs to be while because it governs a whole script repeat..

The problem with such a question is, in the logic of the loop I posted, it would return me something like:

1 = L
2 = u
3 = c
4 = a

And in case I didn’t really want him to read the array this way, why is it just reading the last item of the array, value by value (letter by letter in the case) and showing me on the screen at their respective positions.

In case I wanted it to be printed in such a way:

1 = João
2 = Fernando
3 = Jacinto....
4 = Lucas

Using the loop, what would be the logic for this to be accomplished?

  • can be done with a for instead of a while?

  • Hello Lucas, first welcome to Sopt. As for your question, I know you tried to represent it in the best possible way, but always try to post your piece of code that encompasses the whole solution to facilitate the understanding of everyone. As to need if a while, this structure that is using for the while is equivalent to there is a for or foreach, then it would make no difference to use one or the other, even by the context a for or foreach would be more appropriate.

  • I believe you can yes, I can try to change the script to fit the code using for, what would be the idea?

  • All right, I’m going to do an edit on the topic itself, adding a little more code and details so I was easier to help myself. Thankful!

  • @Lucas, I posted an answer, see if this helps you please, if so, please mark the question as correct.

1 answer

2


In the form below, all your information will be displayed in the correct way:

<?php
$nomes = Array("João Paulo", "Maria Silva", "José Santos", "Pedro Matoso");
foreach($nomes as $nameC)
    {
        echo " => " . $nameC . "<BR>";

    }
        ?><br /><?php
        print_r($nomes);// Irá mostrar tudo o que estiver dentro do array
        ?><br /><?php

        $count = count($nomes); // Irá realizar a contagem através da variável definida
        printf($count); // Retornará a quantidade de posições do array.
        ?><br /><?php
        print_r(reset($nomes)); /*cAqui irá retornar a primeira posição do array devido ao uso do reset */
        ?><br /><?php
?>

The output of this code will be:

=> João Paulo
=> Maria Silva
=> José Santos
=> Pedro Matoso

Array ( [0] => João Paulo [1] => Maria Silva [2] => José Santos [3] => Pedro Matoso )
4
João Paulo

See a functional example in phpfiddle.


As we speak in the comments of this post, every interaction with the variable $nomeC should be done within the foreach, in this way:

<?php
$nomes = Array("João Paulo", "Maria Silva", "José Santos", "Pedro Matoso");
foreach($nomes as $nameC)
    {
        echo " => " . $nameC . "<BR>";
        echo ($nameC . "<br>");
        var_dump($nameC . "<br>");
        echo ("<hr>");

    }
?>

I noticed that you are trying to access variable position for the foreach:

printf($nameC[1]);

This variable, after exit pain foreach has only one position, which would be the last name on the list of array primary.

If you want to print a number before each name, use as below:

foreach($nomes as $nameC)
{
    echo  $contador . " => " . $nameC . "<BR>";
    echo ($nameC . "<br>");
    var_dump($nameC . "<br>");
    echo ("<hr>");
    $contador++;
}

The exit will be:

1 => João Paulo
João Paulo
string(15) "João Paulo
"
2 => Maria Silva
Maria Silva
string(15) "Maria Silva
"
3 => José Santos
José Santos
string(16) "José Santos
"
4 => Pedro Matoso
Pedro Matoso
string(16) "Pedro Matoso
"
  • Right, right, I followed that same logic for my code, however, there are a few points: 1 - The array is populated through the values typed in an input(text) of a web page. 2 - After the array is populated, I make a variable receive the value of all arrays in sequence to follow such logic of the code you posted, but when giving an echo/printf to verify that the variable ta receiving all values, it only prints me the value of the last block of the array, in your example, would only print for me "Pedro Matoso"): and I don’t know why

  • No problem, in this case, I’m setting values for him, but in case you’re picking them up by $_POST, just keep doing the way you’re doing today. Or post the code from when the variable arrives by $_POST until the time to do the for please

  • I will finish editing the post, more consistently, with the codes, the way the variable receives the values and etc.. and if you can, you give a check

  • Ué ): I did exactly this, but it reads the last value of the array, as if it were counting the letters, 1 by 1 D:

  • @Lucas, I look forward to the full edition of your code so I can help you better then

  • @Lucas has already validated with a var_dump or similar if your POST is correctly filling the variable with all past data? Hard to be sure without the code, but I believe that your array should actually contain only one piece of information. Maybe it’s not a problem in loop.

  • @Jaksonfischer ready, I gave an edited, I think it gives to understand where the error is

  • @Viniciusgabriel then, I edited it in the topic, it should be exactly that, but as I explained there, inside the foreach it returns me all the values of the array, but when I print referring to the variable $nameC, it returns only the last value ):

  • @Lucas, I edited the answer, look how it turned out.

  • I understood the logic and helped me to remove some doubts, however the problem now is only 1. It is that as the array is filled in the web page, I have to pull the values from there via $_POST the problem is that for this I need to use the foreach, inside the foreach I make the values to be assigned to the variable "$nameC" and give a print, thus returning all the values of the array, so far, perfection! However, the problem arises when I print OUT OF FOREACH, at that point the variable $nameC only the last value of the array returns to me. http://phpfiddle.org/main/code/rkrc-12yc in this sense

  • @Lucas, understand this, the code will do all the foreach and only after the completion of it, will he interpret the other lines. As he told all and number the count() was 4, it will define that from this point the variable $nomeC receives the value of the last value of the traversed array, in the case of the example the name Pedro Matoso. This will always happen because he has stopped in this position within the foreach. Whichever echo, printf or print_r that needs to be done, you must do inside for each itself. I will add an addition of code to what I did.

  • @Lucas, what would be the need you would have to give a printf in the names outside the foreach? If you can explain this to me, maybe I can help you more

  • @Jaksonfischer It is that in this case it is a script for a 'forum' of the company, where the user type in the web page (in inputs) the description of the problem and automatically opens a topic with what he typed, in the forum, using the API of the same. So I linked the API with the PHP script, in which case what the user type is assigned to the variables and these variables fit the API code. In this case, the script opens several threads automatically, and I want each one to be opened differently from the previous one, in case the user wants to open 3 threads with different problems[+]

  • it would only click on a "+", open a new input for it on the page and it would fill in, then in case the array serves to sort the information that will go to the topic, so in a basic example: User type in inputs; |input1: nome: João| |input2 nome: Fernando|, by clicking submit, it will open two topics, one with the name "João" and the other with the name "Fernando"

  • @Lucas, get into this hall, we will try to expedite your problem

  • @Jaksonfischer right kkkkkkkk I’m there, but I have no idea where the field is for me to type..

  • Now I drew "You must have 20 reputation on The Stack Exchange Network to speak here. See the FAQ ." ):

  • @Lucas, try again, I gave +1 on your question so we can talk there

Show 14 more comments

Browser other questions tagged

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