Searching an object

I need to get search if a fingerprint exists in Stripe’s list of card ( ), I did below:

 $cards = $cu->sources->all(array('object' => 'card'));
 $found = false;
 foreach ($cards->data as $card) {
          if ($card->fingerprint == $fingerprint){
              $found = true;

 if (!$found) {
     // do something

Is it a correct way to check if it exists or doesn’t exist or can you suggest any better way?

I would just do

foreach ($cards->data as $card) {
  if ($card->fingerprint == $fingerprint){
//do something if found
else {
// do something if not found

if you don’t need to do something if found

if ($card->fingerprint != $fingerprint){

No, that’s wrong, because I don’t want to “do something” if found or NOT found several times within a foreach! Only once I want to do that when it searched all the loop. I don’t need to do something if found, just need to do something once if NOT found in entire loop. Any better idea?

array_filter() - get all elements with a matching fingerprint

array_reduce() - start with a boolean and change it only if a fingerprint is found

FilterIterator & iterator_to_array() - if $card is an object

Actually, I wouldn’t change a thing.

Pros of this approach:

  • Performance: You stop iterating after a match was found
  • Readability: Easy to understand

Cons of this approach:

  • Performance: You’re getting all cards from the API

I don’t know the API you’re using. Is it possible to find a card by fingerprint? If not, this is probably most efficient.

@Dormilich Please give a code example.
@timseverien I am not getting several thousands cards from api, just cards of a customer, a customer indeed will not have more than 10 cards!

the code examples are on the linked sites.

since I know from JS that intuition can lead to false assumptions I did some quick testing:

  • for small arrays (100 integers) foreach/break was usually fastest, but all 3 tested functions were far below 1 µs
  • for larger arrays (10,000 integers) there was no clear winner. all 3 functions were in the range of 1 – 5 µs with each function being first in several runs

conclusion: performance-wise it doesn’t matter which one you use. your bottlenecks are likely somewhere else.

Fair point to test the claims. If we’re at it, I don’t think iterating through an array of integers is a good representation of the case as described by @nimasdj. There is also a variable factor; the index of the object that may or may not be found.

But, as @nimasdj later put, the list only contains about 10 elements max, so I doubt performance will be an issue here. The answers you provided are equally good, perhaps better because they are easier to read :slight_smile:

I’m aware of that, but creating an array of 10,000 different integers is easier than creating an array of 100 different objects.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.