0

I have a weird result in PHP.

if( $mandatory_param === "name" ){
    var_dump( $data );
    exit();
}

//output : array(6) { ["name"]=> string(4) "plan" ["class"]=> string(33) "Path\Plan" ["dbtable"]=> string(5) "plans" ["getter"]=> string(7) "plan_id" ["editable"]=> string(4) "true" ["slug"]=> string(2) "pl" } 

But when I try the empty function to test the array, the result change even if the first output show this : ["name"]=> string(4) "plan"

if( $mandatory_param === "name" && empty( $data[ $mandatory_param ] ) ){
  var_dump( $data );
  exit();
}

//Output : array(0) { }

Why ? The empty() function seems to empty my array not to check if it´s empty.

4
  • $mandatory_param is a simple variable or array ...? Commented Jun 9, 2018 at 19:14
  • $mandatory_param is a simple variable which contains only the string. I have just check it. Commented Jun 9, 2018 at 19:17
  • My program needs to detect if the mandatories parameter are empty or not. And for the case of 'name', I have this weird result. Commented Jun 9, 2018 at 19:20
  • This question will marked as low quality. Please provide more information about $mandatory_param and $data. Commented Jun 9, 2018 at 19:49

1 Answer 1

2

Without the complete code it's impossible to say for sure, but to make an educated guess:

When you don't have the empty() check, the exit() is triggered the first time you call the piece of code / function, and $data is set.

When you add empty, the previous call that ended up inside the if-statement does not do so any longer (since name is set for that array), and thus, doesn't produce any output or a call to exit(so the code keeps running).

The code then runs until the test is performed with an array that doesn't have $data['name'] set, performs a var_dump (on what is now an empty array) and exits.

Your call to empty does not remove anything, you're just dumping a different set of data later in your application's run.

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

2 Comments

Do you think it´s because this code is inside a method of a trait that I use for several objects ?
It's because the code is being called multiple times, and when you exit() the first time, you're calling it with different parameters than when it calls exit() in your second example. In the first case it never reaches the code that triggers the valid empty check, as it exists regardless of whether $data['name'] is present.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.