0

I have simple PHP array with data from checkbox. I need add values into array and then insert data into database. It works but foreach not infringement parameter.

So i testing with increment:

$arr = array();
array_push($arr, $_POST['chbox']);

and it looks like 123,125 in array (two elements) Next step is to return number of elements (or values in next step):

$id=0;
foreach(  $arr as $row)
{
    $id++;                              
};

and returns $id=1;

if i'm trying read values:

foreach(  $arr as $row)
{
    $row[$id]   
    $id++;
};

Return only 123

4
  • use $arr = $_POST['chbox']; Commented Mar 4, 2016 at 17:02
  • 1
    This is so weird. How would you know that $row[$id] returns that? There is no echo. Also, if you just want to turn string keys to numeric, take a look at array_values. Commented Mar 4, 2016 at 17:14
  • Wow, a lot of stabs at this. Right after your array_push, do a var_dump($arr); - what do you get? Then a foreach should be simple: foreach($arr AS $i => $row) {echo $row[$i];}. NOTE - if the $_POST is a checkbox, AND the checkbox is NOT checked, then that $_POST key will be EMPTY, and will not actually return anything. Commented Mar 4, 2016 at 17:15
  • Also to get the number of elements, use count($arr) Commented Mar 4, 2016 at 17:18

4 Answers 4

2

If you are doing a foreach, $row is the value already.

foreach($arr as $row) {
    echo $row;
    $id++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

in php, a loop "body" should not end up with semicolon
1

In your foreach() loop, $row is just one array value. Not the array. Replace with $arr should solve.

$id = 0;
foreach( $arr as $row ){
    echo $arr[$id];
    $id++;
}
echo 'Total items: ' . $id; // OR count( $arr );

2 Comments

Why would you loop with foreach if you are using the key ($id) like that? xD
This is how the OP structured the loop. I'm just correcting his variable mistake.
1
$arr =array(123,125);

foreach($arr as $arrr):
   echo $arrr.',';
endforeach;

Output will be:

123,125,

2 Comments

Why the foreach convention here? Curly-braces are fairly standard - the format you are using is more typical of php embedded in a template.
You use Curly-braces. I just provide example, and It become habit for me to use Colon and semicolon Instead of Curly-braces. :)
1

Just try following

foreach($arr as $row){
     echo $row;
};

Edit 1: Better use var_dump($_POST["chkbox"]) or print_r($_POST["chkbox"]) to see the array you are getting. Then it will be easier for you to decide how to get data.

1 Comment

Can you please explain what is wrong here? For you: pastebin.com/x5aSHMrp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.