1

I have an $checked array, looks like this:

array(2) {
  [0]=>
  array(1) {
    ["id_kategorii"]=>
    string(1) "2"
  }
  [1]=>
  array(1) {
    ["id_kategorii"]=>
    string(1) "4"
  }
}

$category array in foreach looks like:

array(2) {
  ["id"]=>
  string(2) "14"
  ["nazwa"]=>
  string(3) "123"
}
array(2) {
  ["id"]=>
  string(1) "8"
  ["nazwa"]=>
  string(5) "ajaja"
}
array(2) {
  ["id"]=>
  string(1) "4"
  ["nazwa"]=>
  string(23) "ale nie no kurde w dupe"
}

etc........

But it's not typical array like array('1','2','3'); So I think because of it this doesn't work but I don't know...

And I have PHP code like this:

foreach($categories as $category)
            {
                $final .= '<tr>';

                if( in_array($category['id'], $checked) )
                {
                    $final .= '<td>'.form_checkbox(array('name' => 'categories[]', 'value' => $category['id'], 'checked' => 'checked')).'</td>';
                }
                else
                {
                    $final .= '<td>'.form_checkbox(array('name' => 'categories[]', 'value' => $category['id'])).'</td>';
                }

But always it comes with else, in_array never goes true.

And it should go true for category['id'] when it's 2 and 4.

Why isn't this in_array working properly?

6
  • You need to work with checked array.. Using array_column() you can create a new array and then in_array() will work fine Commented Jun 29, 2017 at 14:07
  • What do you mean I have to work with? Commented Jun 29, 2017 at 14:07
  • @FrayneKonok I don't understand your point or idea, why creating new column? Commented Jun 29, 2017 at 14:09
  • Your checked array should be like: array('2','4') right? Commented Jun 29, 2017 at 14:09
  • It's going in foreach like in first each checking for 14 == 2, no, then 14 == 4, no, else. But when we have 4 in as $category['id'] True, beacuse we have 4 in $checked[1]['id_kategorii'] Commented Jun 29, 2017 at 14:13

1 Answer 1

2

You need to reform the checked array using array_column() function.

$checked = array(array('id_kategorii' => '2'), array('id_kategorii' => '4'));
$new_checked = array_column($checked, 'id_kategorii');
print_r($new_checked);

Then use the $new_checked array in your in_array().

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

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.