0

I am selecting checkboxes and want to save in an associative array with current page number $_GET['page_no'] as it's index, but only 1 value goes in, why no other?

$pageno = $_GET['page_no']; //Say page no is 1
$_SESSION['selected_vals'] = array();
foreach($_POST['record_num'] as $throw_rec_nums) {
    $_SESSION['selected_vals'][$pageno] = $throw_rec_nums;
}

What I expect

$_SESSOION['selected_val'] (
   [1] => 24
   [1] => 46
   [1] => 56
)

But I only get 24 even if 3 checkboxes are selected

Note: $_GET['page_no'] is returned as array

4
  • Can you clarify the "but only 1 value goes in" part? Commented Feb 15, 2013 at 17:07
  • Please, post you checkboxes html. Commented Feb 15, 2013 at 17:07
  • @FabianoLothor If am using $_GET['record_num'] it is obvious that am using <input type="checkbox" name="record_num[]" /> Commented Feb 15, 2013 at 17:10
  • What you expect is impossible. You can't have multiples values for a key. Commented Feb 15, 2013 at 17:18

3 Answers 3

3

$pageno is not incrementing. In order for more than one value to be added to the array, it needs to be incremented while in the loop.

A solution would be something like:

$_SESSION['selected_vals'][$pageno][] = $throw_rec_nums;

That way all record numbers would be saved to the array at the page number specified.

Sign up to request clarification or add additional context in comments.

2 Comments

ok but that creates array inside an array and uses incremened index, any idea I can keep 1 for all ? and thank you +1
@CreepyFrog: Arrays can only have one value per key. What you want is impossible.
2

Only 1 value goes in because your are replacing $_SESSION['selected_vals'][$pageno] value on each loop of foreach.

try create a counter to index it

it is a option

$_SESSION['selected_vals'] = array();
$_SESSION['selected_vals'][$pageno] = array();
foreach($_POST['record_num'] as $throw_rec_nums) {
    $_SESSION['selected_vals'][$pageno][] = $throw_rec_nums;
}

1 Comment

Is impossible to index all with 1 ... (think with me) how can you access some value if all is index in same key? like you expect, with value may return $_SESSION['selected_val'][1]?
0

You cannot use an array as array index. You will have to iterate over $pageno too, for example with next():

$array[current($pageno)] = ...;
next($pageno);

Note that this will only work if you make sure rt that $pageno actually IS an array and contains enough elements.

2 Comments

I am using foreach so the value returned is not an array :)
But you don't foreach over $pageno and said that was an array. Well, now I see your expectation, this is just impossible. Keys are unique.

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.