2

I'm trying to do the in_array inside of an If else statement. Where it checks if the value exists in an array or not.

Here's how I get the array values from ajax to controller

$data_days = $request->dataDays;

Sample output: 1,2,3,4,5,6,7

If the user didn't check monday and the rest of the days are checked it will return the array like this 2,3,4,5,6,7

These numbers are the number of days

1 = Monday

2 = Tuesday and so on..

and it comes from multiple checkboxes.

Well it works fine when the value matches inside of an array. But when the value isn't exists inside of an array it returns an error which says in_array() expects parameter 2 to be array, null given because the value that I'm matching with my array isn't exists or null

  if (in_array('1', $data_days, true)){
    $message = "exists";
   }
  else{
    $message = "doesn't exists!";
   }

If there's no 1 value inside of an array it should return the doesn't exists! where as of now it just give me an error like this

in_array() expects parameter 2 to be array, null given

1
  • If no check boxes selected then the form will not post it. !empty() & in_array() should fix the issue. Commented May 20, 2019 at 4:49

2 Answers 2

2

Based on Manual:-

in_array()

strict

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

So it's try to check string '1' type inside array, and since there is no value related to it, it gives you NULL error message

Also use 1 instead of '1'.

you have to check !empty()

if (!empty($data_days) && in_array(1, $data_days, true)){ // use numeric value 1, not string

Or use count() with isset()

if ( isset($data_days) && count($data_days) > 0 && in_array(1, $data_days, true)){

Or use sizeof() with isset()

if ( isset($data_days) && sizeof($data_days) > 0 && in_array(1, $data_days, true)){

References:-

empty()

count()

isset()

sizeof()

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

1 Comment

The first solution is enough. The others not needed. Also you should add the reason why it is null.
2

That is not because of the lack of existence of value inside the array.

It seems your array is not creating in a proper way.

But if you are sure about your array which is absolutely correct, check whatever your variable is an array or not.

using is_array() function of PHP.

PHP: is_array - Manual

see:

 if (is_array($data_days) && in_array('1', $data_days, true)){
    $message = "exists";
   }
  else{
    $message = "doesn't exists!";
   }

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.