DEV Community

Imam Ali Mustofa
Imam Ali Mustofa

Posted on

Chill With Searching and Loading

If you have 50,000,000 or more records contained in a variable and you want to look up the data from array by key and get a value similar to what you are looking for. What would you do?

Are you going to use untested code like this

<?php

$lotOfData = ['name' => 'I am stupid', ... , 'name' => 'Yes, I Am'];
$searchTerm = 'am';

foreach ( $lotOfData as $key => $value ) {
   if ( strpos($value, 'am') ) {
      return $value;
   } else {
      return "What ur looking for?!";
   }
}
Enter fullscreen mode Exit fullscreen mode

Or using code like this?

<?php

function search( $array, $key, $value ) {
    $search = "/$value/i";
    $results = array_filter( $array, function( $a ) use( $search )  {
        unset( $a[$key] );
        return preg_grep( $search, $a );
    });
    return $results;
}

$lotOfData = ['name' => 'I am stupid', ... , 'name' => 'Yes, I Am'];
$searchTerm = 'am';

$search_result = search($lotOfData, 'name', $searchTerm);
Enter fullscreen mode Exit fullscreen mode

Which code will you choose? If you have your own way to find similar data in arrays, please tell us how. It looks stupid, but YES that's ME. Spreading ignorance in orderly disorder.

Top comments (0)