1

I am really tearing my hair out and I wondered if anyone can see what I am doing wrong. I have a form which fills an array "Rehearsals". So far so good. If after I press submit, I recover the values of rehearsal, I can get a print_r of the variable, but the variable itself has no contents so:

$rhearsal = $_POST['rehearsal'];
foreach($rhearsal as $row) {
    print_r($row);
    echo "<br>plan:" . $row->plan . "<br><br>";
}

Gives the output:

Array ( 
    [Name] => A***** M***** 
    [Rehearsal_no] => 1 
    [Rehearsal] => Spring15-150106-1900 
    [plan] => Yes 
    [actual] => Yes 
) 
plan:

In other words, the variable exists in $row when I print it using print_r, but when I try to access it with $row->plan it has a null value.

I have done this lots of times before with variables, but not with input forms. If it is any help, the input form is of the form: <input type='hidden' name='rehearsal[$counter][Name]' value='$usern'>where $counter is an incrementing counter.

Anyone got any ideas - I have wasted a day trying to figure this out - typing and retyping in different ways. Thanks :)

2
  • 5
    $row['plan'] since $row is an array, not an object Commented Jan 30, 2015 at 14:43
  • You must not be using: error_reporting(E_ALL); ini_set('display_errors', '1'); Commented Jan 30, 2015 at 15:38

2 Answers 2

4

Change your code to this:

$rhearsal = $_POST['rehearsal'];
foreach($rhearsal as $row) {
    print_r($row);
    echo "<br>plan:" . $row['plan'] . "<br><br>";
}

More importantly, this bit:

$row['plan'];

As $row is an array, you grab it this way.

Objects are grabbed by using ->.

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

2 Comments

Brilliant - thanks. Just goes to show it pays to ask. I am still not sure what the difference between an array and an object is, but I will do some further research. :)
@Mishutka if this answer has helped you can you please press the tick to the left of the answer box to mark it as answered!
0

If you prefer to access the values in $row using the object notation then you can just convert $row to an object:

$rhearsal = $_POST['rehearsal'];
foreach($rhearsal as $row) {
    print_r($row);           // here $row is an array()
    $row = (object)$row;
    print_r($row);           // and now it's an object (stdClass)
    echo "<br>plan:" . $row->plan . "<br><br>";        // this works as expected
}

Comments

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.