user381800
user381800

Reputation:

PHP how to fix Illegal offset type error?

So I have this $_POST which I am trying to check if it is set but when I do that, it gives me the error in the title.

The $_POST contains array within array. So that could be the reason. $_POST has value if the checkbox is checked otherwise nothing is posted.

So example of what $_POST would contain:

array() => 'item-one' => array( 102 ) => 'on'

I am using this in PHP:

function testing( $db_id ) {
    $fields = array( 'one', 'two' );

    foreach( $fields as $field ) {
         if ( isset( $_POST['item-' . $field][$db_id] ) ) {
              // do something
         }
    }
}

Thanks for looking.

Upvotes: 0

Views: 362

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

foreach( $fields as $field ) {
     if (isset($_POST['item-'.$field]) and in_array($db_id,$_POST['item-'.$field])){
          // do something
     }
}

Alternatively you can try it like,

$fields=array('item-one','item-two')
foreach( $fields as $key=>$field ) {
     if (isset($_POST[$field]) and in_array($db_id,$_POST[$field])){
          // do something
     }
}

Upvotes: 1

Julien
Julien

Reputation: 1980

Try with in_array:

$fields = array( 'one', 'two' );

foreach( $fields as $field ) {
     if ( in_array($_POST['item-' . $field][$db_id], $fields) ) {
          // do something
     }
}

Upvotes: 0

Related Questions