Home > Enterprise >  My if statement shows empty when variable is not
My if statement shows empty when variable is not

Time:05-04

This:

dump($signupIds);
    if(empty($signupIds)){
    return response()->json(['message'=>_('Empty')], 422);
    }  else {
    return response()->json(['message'=>_('Not empty')], 422);
    } 

if $signupIds is containing (from the dump):

array:1 [
  0 => ""
]

it says Empty and if $signupIds is:

array:2 [
  0 => "52"
  1 => "51"
]

or

array:1 [
  0 => "51"
]

it also says Empty.

What is wrong here?

I dont understand how to do that. The statements that build the $signupIds you can see here:

        $signupIds = null;
        $signupsSelected = ($request->exists('signup_ids'));
        if ($request->has('signup_ids')) {
            $signupIds = explode(',', $request->get('signup_ids'));
        }

CodePudding user response:

When you use the empty() function for both arrays you use, it should return false. Because they both have elements in them. Alternatively, it would make more sense to use the count() method.

For example :

<?php 
   
// Declare an empty array 
$empty_array = array();
   
// Function to count array 
// element and use condition
if(count($empty_array) == 0)
    echo "Array is empty";
else
    echo "Array is non- empty";
?>

CodePudding user response:

I found out this:

    if(in_array("", $signupIds)){
    return response()->json(['message'=>_('Empty')], 422);
    }  else {
    return response()->json(['message'=>_('Not empty')], 422);
    }

is what needed. This because the array consists of either "" ie empty or "23", "44" and so on that contains valuable data.

So now it works. Thanks a lot guys!

  • Related