Should I use if-else in using whereIn()

148
April 19, 2018, at 2:30 PM

$search_val is array when it has two or more values. But when $search_val has only one value, $search_val is not array. It will be number.

In this case, should I use if-else?

case1: not use if-else

$query->whereIn('column', $search_val);

case2: if-else

if (is_array($search_val)) {
  $query->whereIn('column', $search_val);
} else {
  $query->where('column', $search_val);
}
Answer 1

I think the question has some interesting aspects that need to be answered in order to form a proper answer.

Can whereIn function take a scalar (i.e. non-array) value?

From Laravel's code here, it doesn't handle scalar values. So this means we have to supply an array - and therefore means that your Case 1 above will not work.

Can if/else statements be used to determine where to use whereIn or where?

Of course! But eventually the length of your function (in terms of number of lines) grows when the actual usefulness of the function doesn't increase one bit.

You could do it in one line:

$query->whereIn('column', is_array($search_val) ? $search_val : [$search_val]);

Which makes things slightly neater. But my guess is that eventually you might end up (perhaps elsewhere) with such checks more often than you'd like. In fact, that could be considered a code smell.

Fix the source of the problem

My suggestion would be to fix the source of the problem - the function or piece of code that returns either an array or a scalar value. Make it always return an array. If it's only a single value, make it convert that into a one-element array.

Answer 2

how about this?

$query->whereIn('column', is_array($search_val) ? $search_val : [$search_val]);

Rent Charter Buses Company
READ ALSO
Creating transparent PNG images in PHP with GD leaves fuzzy edges

Creating transparent PNG images in PHP with GD leaves fuzzy edges

I have a transparent logo in a png fileI'm trying to create a transparent box image which would be the background for the logo

153
Get browser width using php

Get browser width using php

Is there a way to get the screen size through php? I have had a look on google, and found a way of doing it through javascript as follows:

303
Conditional Product Display OpenCart

Conditional Product Display OpenCart

I am new to Open Cart and have been trying to work out how I should go about creating a Custom bit of functionality

181
Strip or Change User-Agent while using Header() Function to Redirect

Strip or Change User-Agent while using Header() Function to Redirect

Is it possible to alter the User-Agent string before redirecting to a location in PHP with header('Location: https://examplecom/')?

160