0

Here is what I have, I know I can rewrite my conditional syntax but I just wanted to see if there was something else I can do with what I have.

$sleeping[] = ($a->day_bed == 1) ? 'Day Bed' : false; $sleeping[] = ($a->fold_up_bed == 1) ? 'Fold Up Bed' : false; $sleeping[] = ($a->murphy_bed == 1) ? 'Murphy Bed' : false; $sleeping[] = ($a->trundle_bed == 1) ? 'Trundle Bed' : false; 

I'm trying to test for an empty array or not and rather than an empty array I get:

Array ( [0] => [1] => [2] => [3] => ) 

This never registers as "empty". As far as I can tell I need the "else" syntax on there otherwise it fails.

Is there something else I can use besides NULL or FALSE? Or any other way to format it? I like this format because I have around 600 of these and it makes it much easier to read. Any suggestions?

1
  • 2
    You should use var_dump instead of print_r, you would see that the array contains false. Commented Aug 16, 2014 at 13:11

2 Answers 2

2

You'll have to change the format as the check for existence needs to happen before you push another element onto the array. This should work:

if ($a->day_bed == 1) $sleeping[] = 'Day Bed'; 

You can save yourself lots of work by automating this task, eg like this

$bedTypes = array( "day_bed" => "Day Bed", "fold_up_bed" => "Fold up bed" ); foreach ($bedTypes as $key=>$val) { if ($a->{$key} == 1) $sleeping[] = $val; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Alright that seems just as clean guess I'll change it to that. Thanks!
0

Another alternative is to use array_filter() with no callback to remove all falsy elements in the array:

<?php $a = new stdClass(); $a->day_bed = false; $a->fold_up_bed = false; $a->murphy_bed = false; $a->trundle_bed = false; $sleeping[] = ($a->day_bed == 1) ? 'Day Bed' : false; $sleeping[] = ($a->fold_up_bed == 1) ? 'Fold Up Bed' : false; $sleeping[] = ($a->murphy_bed == 1) ? 'Murphy Bed' : false; $sleeping[] = ($a->trundle_bed == 1) ? 'Trundle Bed' : false; $emptySleeping = array_filter($sleeping); if(empty($emptySleeping)) { // here code if the array is empty. } var_dump($sleeping); var_dump($emptySleeping); 

See it in action

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.