db: count() method is returning string not integer

If you use count() method to return the number of rows in your table, you will get the number but as string not integer. You can check that yourself, just var dump the result of your query. Documentation of count() says that it should return integer, and that is what I was hoping for, but got surprised with result. Is this (not)working as intended or I am missing something ?

Docs: http://www.yiiframework.com/doc-2.0/yii-db-query.html#count()-detail

I was doing very simple query $numberOfUsers = User::find()->count();

I use the latest yii2, downloaded today.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 20 (16 by maintainers)

Most upvoted comments

whether there is an abstraction layer between it or not, one expects a count function to return a number, not a string. This is the most intuitive result.

I’d also expect an integer here.

From https://stackoverflow.com/questions/670662/whats-the-maximum-size-for-an-int-in-php even on 32bit systems this would be limited to ~2 billion, which is quite large and on 64bit to ~9 quintillion.

The only con is that we’ll have int|string as a type hint 😦

Numerical string will be returned only in edge cases (when you need integer bigger than your environment can handle). We could:

  1. Laravel style - f*ck edge cases and always cast to int.
  2. Remove string from typehint - in 99.9999% cases you will get int anyway, so string in typehint may give more harm than good.

@ptz-nerf This is not a code sample. How do you want to use === on comparing result with integer that cannot be represented as integer?

I would say that we should do it a long time ago. W can safely convert count() result to int, so there is no technical problem here.