2

I have an input wich is an array, the key of the array is the lang id like this

<input type="text" name="name[{{ $lang->id }}]">

this field is optional, so i don't whant to validate if it is or not, what i want is to check if both element of the array are empty do something. Lets supose this is the input name[]

{
    "1": null,
    "2": null
}

i can't do

if($request->has('name')) {
    //do something
}else {
    //do another thing
}

Because the $request has a name, is there a way to do something like this

if(array_is_empty($request->has('name'))) {
    //do something
}else {
    //do another thing
}
1
  • 1
    if(empty(array_filter($array)) , You can also do empty(array_filter(array_map('trim',$array))) if you want to consider spaces empty Commented Sep 2, 2018 at 0:04

2 Answers 2

2

$imply use array filter which will remove any empty or falsey items from the array, then check if anything is left:

if(empty(array_filter($array)))

If you want to consider spaces empty, for example someone just puts blank space in the field you can throw in an array map with trim as the callback, like this:

 if(empty(array_filter(array_map('trim',$array))))

Test It

$a = [
    "1" => null,
    "2" => null
];

if(empty(array_filter($a))) echo 'empty';

Output

 empty

Sandbox

array_filter — Filters elements of an array using a callback function Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

PHP will consider several things as falsy and remove them, you can supply your own callback if you need finer control, but some of things considered falsy

0
"0"
""
false
null
[] //this is what you get after filtering $array

There may be others, but this should give you the idea.

Because array filter returns an empty array [] which is also falsy you can even just do this if you don't want to call empty

if(!array_filter($array)) 

But it makes the code a bit less readable because it depends on PHP's loose typing where when empty is used the intent is crystal clear.

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

Comments

2

The Laravel validator has an nullable rule for validation on fields that are optional.

https://laravel.com/docs/5.6/validation#a-note-on-optional-fields

And can validate arrays.

https://laravel.com/docs/5.6/validation#validating-arrays

So you might do...

 $request->validate([
   'name.*' => 'nullable|string',
 ]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.