0

I am having a problem with a session multi-dimensional array I am trying to add values to. I am told that I should state the array "before" I start adding values, but when I do that the array is treated like a normal array without being a session. Thus, that will not work for my case. At the same time, the code error is ruining my code. I have no idea how I can solve this problem.

Here are the code lines which are causing the error message

Warning: Cannot use a scalar value as an array

(Of course I have more code than this, these are just the lines that affect the issue):

PHP:

for($i=0; $i < count($_POST['part_number']); $i++) {
$_SESSION['qty'][$i] = $_POST['qty'][$i];
}

HTML:

<input type="text" value="1" name="qty[0]" size="2" />
6
  • ['qty'] needs to be an array before you set values to it Commented Nov 19, 2013 at 17:52
  • What is $_SESSION['qty']? Try: var_dump($_SESSION['qty']);. Commented Nov 19, 2013 at 17:53
  • @RUJordan, Like I said, then the array is treated as a regular array instead of a Session, correct? Commented Nov 19, 2013 at 17:53
  • Check for existence of $_SESSION['qty'] and if exists check it's type with is_array() ... if it's an array you should be able to alter it, if not it must not be set, so create a new array. Commented Nov 19, 2013 at 17:54
  • Are you calling session_start? If you don't start it manually and it's not started automatically, then $_SESSION won't be magic. Commented Nov 19, 2013 at 17:55

1 Answer 1

1

Most likely, either $_SESSION['qty'] or $_POST['qty'] is not an array. Try this:

if(!isset($_SESSION['qty']) || !is_array($_SESSION['qty'])) $_SESSION['qty'] = array();
if(!is_array($_POST['qty'])) throw new Exception('Error: $_POST[\'qty\'] is not an array!');
for($i=0; $i < count($_POST['part_number']); $i++) {
    if(!isset($_POST['qty'][$i])) continue;
    $_SESSION['qty'][$i] = $_POST['qty'][$i];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Check your quotes in the exception
Yes, I had to escape the single quotes. However, other than that this worked excellent! Thank you.
@RUJordan Oops, you're right, I forgot to escape the quotes. Fixed now.

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.