Home » Php » laravel – Code doesn't funtion right in PHP 7.3. Best way ti fix where it is backwards compatible with PHP 7.1 and 7.2, count() error

laravel – Code doesn't funtion right in PHP 7.3. Best way ti fix where it is backwards compatible with PHP 7.1 and 7.2, count() error

Posted by: admin February 25, 2020 Leave a comment

Questions:

This is code within a laravel framework

 'mat_tactic_id' => count($request['red-mat_tactic_id']) > 0 ? implode(',',$request['red-mat_tactic_id']) : $request['red-mat_tactic_id'],

Here is the exception

ErrorException (E_WARNING) count(): Parameter must be an array or an
object that implements Countable

I have tried is_Countable and that will fix but only in 7.3 it is not backwards compatible.

Any thoughts?

How to&Answers:

You can check if it is even set and if it is an array like so:

isset($request['red-mat_tactic_id']) && is_array($request['red-mat_tactic_id'])

That means counting would work like this:

count((isset($request['red-mat_tactic_id']) && is_array($request['red-mat_tactic_id'])) ? $request['red-mat_tactic_id'] : [])

To have it better readable you would probably break that into two lines:

$isValueSet = $request['red-mat_tactic_id'] && is_array($request['red-mat_tactic_id'];
count(isValueSet ? $request['red-mat_tactic_id'] : [])

Depending on what exactly the content of the array index is, this could be simplified to:

count($request['red-mat_tactic_id'] ?? [])

Using the null coalescing operator.