غير قادر على تحديد ما إذا كانت السلسلة هي حاليا عدد صحيح أم لا

StackOverflow https://stackoverflow.com/questions/9505466

  •  14-11-2019
  •  | 
  •  

سؤال

يدفعني funciton التالي إلى المكسرات.كيف يمكن أن يكون 100x على الأرض يساوي 100 ثم يتم الإبلاغ عن 100x كعدد صحيح؟ لحياة لي، لا أستطيع معرفة ذلك. يمكنك نسخ ولصق كل شيء ورؤيته بنفسك.
أفتقد نقطة بسيطة في مكان ما هنا، ساعدني في الخروج من الرجال. giveacodicetagpre.

رمز أعلاه، عند تشغيل إرجاع ما يلي؛ giveacodicetagpre.

يمكنني علاج الوضع عن طريق إضافة البتات التالية giveacodicetagpre.

إلى أعلى وظيفة BLP_INT مباشرة قبالة الخفافيش ولكن، ما زلت فضولي للغاية لمعرفة السبب في الأرض PHP يعتقد 100x= 100 يساوي.

هل كانت مفيدة؟

المحلول

As you can see in this example, casting 100x as an integer converts it to 100. Since you are not using strict comparison, '100x' == 100 is true. PHP removes the x from it to make just 100.

You could use strict comparison (which also compares the types), such that '100x' === 100 would return false. Using it, any time a string was compared to an integer, it would return false.


As per your edit: is_numeric may not be the most reliable, as it will return true for numbers formatted as a string, such as '100'. If you want the number to be an integer (and never a string), you could use is_integer instead. I'm not quite sure what exactly you're doing, but i thought I'd add this note.

نصائح أخرى

I think you should use three equal signs in your IF:

if ($orgval===$num) {

Otherwise PHP casts the value 100x to 100 and 100=100.

Documentation: Comparison Operators

What kind of check do you want to do? There are a few ways you could go about it:

if (preg_match('!^[0-9]+$!', $input))

if (intval($input) == $input)

if (intval($input) === $input)

if ('x'.intval($input) === 'x'.$input)

It depends on how closely you want to check if it's an integer. Does it matter if you need to trim() it first?

Either cast it to an int or try http://php.net/manual/en/function.ctype-digit.php. You also need === in your if.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top