0

I want to check if a numeric variable has a value (including '0') and is not empty. Empty meaning EMPTY (''), not '0'.

Is this really the best I can do with PHP?

if (isset($variable) && $variable !== '') { ... }

I'd like to do this with one check without writing a function for it...

D. Joe
  • 9
  • 5
  • `$variable != ' '` replace it. – Jees K Denny Aug 05 '16 at 14:10
  • `isset($variable) AND !empty($variable) AND !is_numeric($variable) AND $variable !== false` – Charlotte Dunois Aug 05 '16 at 14:12
  • @JeesKDenny Check the manual for `empty()` a zero is considered empty, that I assume is whole the point of the question – RiggsFolly Aug 05 '16 at 14:13
  • The first one works, !empty alone does not, because "0" counts as empty. – D. Joe Aug 05 '16 at 14:13
  • Edited. Very thanks I checked. @RiggsFolly – Jees K Denny Aug 05 '16 at 14:15
  • 1
    @D.Joe You could write a custom function for this kind of test,and then re-use it as u want – jbrtrnd Aug 05 '16 at 14:15
  • Yep, I'll call the function... empty() ;-) – D. Joe Aug 05 '16 at 14:19
  • @D.Joe What about `my_kind_of_empty()` – RiggsFolly Aug 05 '16 at 14:21
  • *"I want to check if a variable has a value (including '0') and is not empty. Empty meaning EMPTY (''), not '0'."* - That statement makes no sense at all. The question is about as clear as mud. – Funk Forty Niner Aug 05 '16 at 14:27
  • What literally doesn't make sense is PHP's meaning of "empty" :) I can accept "isset" ignoring 0, but "empty" has a very distinct meaning in the English language and "0", by definition of the word, is not empty. – D. Joe Aug 05 '16 at 14:36
  • Funny, that's not what the question reads as. Btw, have you tried any of the other answers?? You're leaving everyone in the dark here. – Funk Forty Niner Aug 05 '16 at 14:36
  • 1
    See [this](https://stackoverflow.com/questions/2220519/in-php-is-0-treated-as-empty) why `'0'` is considered empty – Charlotte Dunois Aug 05 '16 at 14:38
  • I'm going to the pool now. Or better yet; the "beach". – Funk Forty Niner Aug 05 '16 at 14:41
  • @Fred-ii- Make some photos while you go to the beach ;-) – Charlotte Dunois Aug 05 '16 at 14:42
  • @CharlotteDunois or videos; they show the *real* action ;-) – Funk Forty Niner Aug 05 '16 at 14:43
  • @Fred-ii- Even better! Don't forget to share them with your friends (including me). ;-) – Charlotte Dunois Aug 05 '16 at 14:43
  • @CharlotteDunois I'll have to borrow [*this guy's face...*](https://apastorsheartdotcom.files.wordpress.com/2015/09/the-unknown-comic-2.jpg) just so I don't incriminate myself. :-) *au revoir mon amie* – Funk Forty Niner Aug 05 '16 at 14:46
  • possible duplicate of [In php, is 0 treated as empty?](http://stackoverflow.com/questions/2220519/in-php-is-0-treated-as-empty) – Funk Forty Niner Aug 05 '16 at 15:16
  • The other thread handles a part of the problem and has the solution as unaccepted answer, but is not technically the same question. – D. Joe Aug 05 '16 at 15:19
  • So why the answer then, by you http://stackoverflow.com/a/38792479/1415724 - You are only adding more confusion. – Funk Forty Niner Aug 05 '16 at 15:27
  • `is_numeric` does not do the job. It only works for numbers or *numeric* strings. On regular strings like `hello`, `is_numeric` will return `false`. – Charlotte Dunois Aug 05 '16 at 15:29
  • No, you only want your embarassing flirt attempts deleted, which have no place here. It's a different question with a different accepted answer. – D. Joe Aug 05 '16 at 15:29
  • again... **why the answer??** http://stackoverflow.com/a/38792479/ FFS and stop with the edits, will you? – Funk Forty Niner Aug 05 '16 at 15:30
  • It wasn't accepted there for a reason: It's a different question. – D. Joe Aug 05 '16 at 15:30
  • It doesn't matter; many were upvoted and that in its own right, constitutes as a possible duplicate. If it's a different question, then post another question based on that. – Funk Forty Niner Aug 05 '16 at 15:32
  • You said you were going to the pool. It seems that was a lie. – D. Joe Aug 05 '16 at 15:32
  • 1
    You made an answer to your own question, which isn't even a solution to your problem. – Charlotte Dunois Aug 05 '16 at 15:32
  • I left out some details, just like you *lol* I didn't lie. Thing is, I didn't say "when" I was going. Edit: @CharlotteDunois agreed, +1 on your comment and then some. – Funk Forty Niner Aug 05 '16 at 15:33
  • Don't worry, I'll delete this. Just pointing out I know why you want this deleted, and being a duplicate is not the true reason. It's always the same with Stack users who have many points. When they embarass themselves, they are looking for a reason to get the thread deleted. I'm just quickly archiving this at wayback machine. – D. Joe Aug 05 '16 at 15:37
  • This question should be flagged for deletion. Being a total waste of time on everyone's part. – Funk Forty Niner Aug 05 '16 at 15:43
  • Well, you started the chit chat here by trying to suck up to Carlotte. – D. Joe Aug 05 '16 at 15:44
  • *"Well, you started the chit chat here by trying to suck up to Carlotte."* - I resent that comment. Charlotte's answer was a good one and just because she probably likes me and I think she's pretty cool too, doesn't mean that I favorised her answer. I did also upvote other answers here, so don't go talking nonsense; *thank you*. Oh and why did you (suddenly) unaccept her answer; honestly now? – Funk Forty Niner Aug 05 '16 at 16:17

4 Answers4

2

What you are trying to check is string length, not "empty". This can easily be done using strlen().

if (isset($variable) && strlen($variable) > 0) {
    // Do something
}

If you want to exclude whitespace as invalid, you can add a trim() in there as well (generally recommended).

if (isset($variable) && strlen(trim($variable)) > 0 } {
    // ...
}
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
  • You'll get an warning with this if the variable isn't set prior to your strlen check – Ray Aug 05 '16 at 14:17
  • That's why the `isset()` call is there (I forgot to include it in my original answer). – Jeremy Harris Aug 05 '16 at 14:18
  • See my answer, `strlen` is much less efficient than checking for strong equality to the `''`. In the single case, no big deal, but if in a large loop would matter – Ray Aug 05 '16 at 14:30
2

Yes, your way is the best (most efficient) way to:

  • insure the variable has been set (so you don't get an warning checking a variable that's not been set)
  • it's not the empty string ''
    • But, could be '0', 0,false, null, or [] which all count as empty in php, but you wish to consider as non-empty as indicated by your OP
    • your !== will ensure only exactly the string '' is compared (no casting/conversion)

The use of strlen works as well, but if you look at the opcode generated you'll see direct comparison is more 3 times computationally more efficient (assuming all operations are equally weighted, even more efficient if operations like DO_FCALL take significantly more cycles to execute than a basic IS_NOT_IDENTICAL check)

The !== ''version bytecode:

    IS_NOT_IDENTICAL                                     ~1      !0, ''

The strlen() > 0 version bytecode:

     SEND_VAR                                                 !0
     DO_FCALL                                      1  $1      'strlen'
     IS_SMALLER                                       ~2      $1, 0
Ray
  • 40,256
  • 21
  • 101
  • 138
2

The best thing you could do, is making your own custom function. The point is to pass the variables by reference to not trigger a warning, when you pass an undefined variable. As posted as comment, I'd use something along the line isset($variable) AND !empty($variable) AND !is_numeric($variable) AND $variable !== false to cover all cases.

Your custom function could look like this (improved version):

function is_blank(&$variable) {
    return (bool) !(isset($variable) AND (!empty($variable) OR is_numeric($variable) OR $variable === false));
}

https://3v4l.org/ZcCDu

Charlotte Dunois
  • 4,638
  • 2
  • 20
  • 39
  • Charlotte, OP states in the question (which by my standards is about as clear as mud at midnight with no moon in sight): *"I'd like to do this with one check without writing a function for it..."* - If you get a downvote, I can assure you that it would not have come from me. It's not my style ;-) Good answer though. – Funk Forty Niner Aug 05 '16 at 14:31
  • @Fred-ii- I started writing the answer before he edited the question ;-) Also it says "*The best thing you could do,...*" If he doesn't want that, not my fault. ;-) – Charlotte Dunois Aug 05 '16 at 14:31
  • Yeah I know Charlotte.. *sigh*. Well the OP will have to either clarify the question, try someone's answer and/or post a comment under whatever one worked or not. I won't be adding anything else to mine. Not until I know *which animal* I'm dealing with here exactly. – Funk Forty Niner Aug 05 '16 at 14:33
  • @Fred-ii- Probably a *llama*, but we can't be too sure. This one doesn't wear hats! – Charlotte Dunois Aug 05 '16 at 14:34
  • Only the magician wears the (top) hat. The one that *the rabbit* took off with, before being chased down his (deep) hole. hehe – Funk Forty Niner Aug 05 '16 at 14:35
  • Requiring an extra function is indeed not what I was hoping for, but all things considered seems like the best/only way to make the code cleaner. I need to check several variables and without this it'll be an unreadable mess. – D. Joe Aug 05 '16 at 14:42
  • @D.Joe Yes, it's cleaner and the code gets easier to read. Unless messy code is your thing... – Charlotte Dunois Aug 05 '16 at 14:45
  • 1
    @D.Joe code cleanliness isn't what you asked for. Creating a function is the worse thing you could do computationally. You should change your post to indicate "what would make my code easist to read", but that also is subjective. I think strait comparison to `''` is easier to understand – Ray Aug 05 '16 at 14:45
  • You are correct, should have stated that in the beginning. I do several of these checks so clean code was the main goal and I added that to the question some time ago. I didn't even consider that this isn't possible in PHP with one regular function... – D. Joe Aug 05 '16 at 14:50
  • Actually, I found "is_numeric", which seems better than the other suggestions? Or is there anything wrong with using that? – D. Joe Aug 05 '16 at 14:55
  • @CharlotteDunois I see the OP unaccepted your answer; *wow, rich*. Obviously ticked off. You know what? They should have clarified that (bad) question of theirs from the get-go. Sorry to see the green gone, but hey... they're only points. It's not like you got an arm or a hand or fingers cut off. I on the other hand (no pun intended here), would definitely miss my "fingers"; they keep me happy (it's not what you think..., I mean by playing stringed instruments) ;-) – Funk Forty Niner Aug 05 '16 at 15:42
  • 1
    @Fred-ii- Don't worry, I'd definitely miss my fingers too! – Charlotte Dunois Aug 05 '16 at 15:44
1

(The answer has been edited. Consult the additionals further down under "ternary operations").

Why go through the trouble of using all that?

Just use an "not empty" if(!empty($var)){...}

However, if you're using this with a GET array, then yes; it would be best to use an isset() and empty() on a conditional statement.

I want to check if a variable has a value (including '0') and is not empty

That to me interprets as:

Check if a value has a value and is not empty (as you wrote) and stands to contain a 0 (zero).

Therefore:

if(!empty($var) && $var='0'){...}


I'd like to do this with one check without writing a function for it...

Use a ternary operator then.

However "without a function"... right well you can't. You still need "some type of function".

About that "ternary operator" I mentioned above. You can reference what are called "nested ternary operations" in both these Q&A's on Stack:

That way you won't need a custom function.

  • Sidenote: I am by far not taking away or trying to take away from (Charlotte's) accepted answer (which should remain as accepted). This is just an additional method of achieving your (ultimate) goal.
Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141