search
HomeBackend DevelopmentPHP TutorialSummary of various methods of finding array elements in PHP_PHP Tutorial

Summary of various methods of finding array elements in PHP_PHP Tutorial

Jul 13, 2016 pm 04:57 PM
phpandelementClassificationCanexistmultidimensionalSummarizedata queryarraymethodcheckFind

Data query in php can be classified into one-dimensional array search and multi-dimensional array search. If it is a simple one-dimensional array, we can directly use in_array, array_search and traversal to instantiate it. If it is a multi-dimensional array, we need to use other methods. .

For a one-dimensional array we can operate as follows

in_array 'Function searches for a given value in an array. in_array(value,array,type)type optional. If this parameter is set to true, it is checked whether the type of the searched data and the value of the array are the same.

array_key_exists 'array_key_exists() function determines whether the specified key exists in an array. If the key exists, it returns true, otherwise it returns false. array_key_exists(key,array)

array_search 'array_search() function is the same as in_array(), searching for a key value in an array. If the value is found, the key of the matching element is returned. If not found, returns false. array_search(value,array,strict)

From this point of view, when the amount of data is not large, such as less than 1000, any search method can be used, and it will not become a bottleneck;
When the amount of data is relatively large, array_key_exists is more appropriate.
Of course, the memory occupied by array_key_exists here is relatively large. According to calculations

Binary method to find whether an array contains a certain element, compatible with forward and reverse order, code implementation:

The code is as follows Copy code
 代码如下 复制代码

$searchValue = (int)$_GET['key'];

function search(array $array, $value)
{
$max = count($array)-1;
$min = 0;
$isAscSort = $array[$min]

while (TRUE) {
$sum = $min+$max;
$midKey = (int)($sum%2 == 1 ? ceil($sum/2) : $sum/2);

if ($max return -1;
} else if ($value == $array[$midKey]) {
return 1;
} else if ($value > $array[$midKey]) {
$isAscSort ? $min = $midKey+1 : $max = $midKey-1;
} else if ($value $isAscSort ? $max = $midKey-1 : $min = $midKey+1;
}
}
}

$array = array(
'4', '5', '7', '8', '9', '10', '11', '12'
);
// 正序
echo search($array, $searchValue);

// 逆序
rsort($array);
echo search($array, $searchValue);

$searchValue = (int)$_GET['key']; function search(array $array, $value) { $max = count($array)-1; $min = 0; $isAscSort = $array[$min] while (TRUE) { $sum = $min+$max; $midKey = (int)($sum%2 == 1 ? ceil($sum/2) : $sum/2); if ($max return -1; } else if ($value == $array[$midKey]) { return 1; } else if ($value > $array[$midKey]) { $isAscSort ? $min = $midKey+1 : $max = $midKey-1; } else if ($value $isAscSort ? $max = $midKey-1 : $min = $midKey+1; } } } $array = array( '4', '5', '7', '8', '9', '10', '11', '12' ); // Positive sequence echo search($array, $searchValue); //reverse order rsort($array); echo search($array, $searchValue);

Example 2

PHP Find the i-th smallest element in an array

The code is as follows Copy code

​​ #Randomly select the i-th smallest number and use random quick sort to achieve
​  
​​ #Exchange elements
Function swap(&$arr, $i, $j) {
           $temp = $arr[$i];
           $arr[$i] = $arr[$j];
           $arr[$j] = $temp;
}

​​ #Randomly divided
Function randomized_partition(&$arr, $begin, $end) {
           $rand_inx = rand($begin, $end);
            swap($arr, $begin, $rand_inx);
            return partition($arr, $begin, $end);
}

​​ #Division
Function partition(&$arr, $begin, $end) {
​​​​ #Use the first element as the central element
            $pivot = $begin;
           $low = $begin;
           $high = $end;

​​​​​while ($low                   while ($low                      $low++;
             }

                    while ($low = $arr[$pivot]) {
$high--;
             }

                 swap($arr, $low, $high);
         }

           #Exchange hub element
If ($arr[$pivot]                  $low--;
         }
            swap($arr, $pivot, $low);
          return $low;
}

​​ #Quick sort, not used here
Function quick_sort(&$arr, $begin, $end) {
            $q = randomized_partition($arr, $begin, $end);
If ($q > $begin) {
                quick_sort($arr, $begin, $q - 1);
         }
              if ($q                 quick_sort($arr, $q + 1, $end);
         }
}

​​ #Select the i-th smallest number
Function randomized_select(&$arr, $begin, $end, $i) {
             if ($begin == $end) {
                 return $arr[$begin];
         }

            $q = randomized_partition($arr, $begin, $end);
            $k = $q - $begin + 1; #k represents the number of elements less than or equal to q

               if ($k == $i) { #If k=i, it means that q is the coordinate of the i-th smallest element
                 return $arr[$q];
                                                                                                                  {                  return randomized_select($arr, $begin, $q - 1, $i);
             } else { #The i-th smallest element is located on the right side of q. At this time, find the i-kth smallest element on the right
                  return randomized_select($arr, $q + 1, $end, $i - $k);
         }
}

$arr = array(1, 5, 3, 7, 0, 0, 8, 4, 2, 9, 11);
$t = randomized_select($arr, 0, count($arr) - 1, 8);
Print_r("The 8th minimum element: {$t}");
echo "
";
Quick_sort($arr, 0, count($arr) - 1);
Print_r($arr);
?>

http://www.bkjia.com/PHPjc/631562.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631562.htmlTechArticleData query in php can be classified into one-dimensional array search and multi-dimensional array search. If it is a simple one-dimensional We can directly use in_array, array_search and traversal to instantiate arrays, such as...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools