experimenting with refactoring some old code and figured I would experiment with apiv4. the first hurdle was figuring out how to use the ArrayObject that is returned.

in apiv3, for example I would look at the count value in the array. in apiv4 there is no such value.

my api v3 call looks like this

  $result = civicrm_api3('Contact', 'get', array(
  'return' => array("custom_90", "custom_91", "custom_85", "custom_88", "custom_143"),
    'id' => $alum_cid,
    'custom_143' => $sal['id'],
  if ($result['count'] != 0) {
    do things

my apiv4 call looks like this

$results = \Civi\Api4\Contact::get()
  ->addWhere('id', '=', $alum_cid)
  ->addWhere('Employment_History.relationshipID', '=', $sal['id'])

how do I get the count of the results?

2 Answers 2


See https://docs.civicrm.org/dev/en/latest/api/v4/usage/ where it says:

  • $result->count(): get the number of fetched (if LIMIT used) or matching results (if row_count included in select).
  • From CiviCRM 5.50+ $result->countFetched(): get the number of fetched results. If you used LIMIT this won't exceed that number (but could be less).
  • From CiviCRM 5.50+ $result->countMatched(): get the total number of matching results. If you only fetched a subset (with LIMIT) you are required to add row_count to the select clause.

the way the api works now, the thing returned is an ArrayObject which you can call functions on, one of those is count()

so just count the results; and then loop over them as you would if it was a normal array

  if (count($results) != 0) {
    foreach ($results as $result) {
      do things


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.