Example of PHP Custom Function Realizing Array Comparison Function

  • 2021-08-10 07:23:14
  • OfStack

This paper describes the example of PHP custom function to achieve array comparison function. Share it for your reference, as follows:


<?php
 // Arrays are compared using standard comparison operators 
 function standard_array_compare($op1,$op2)
 {
 if(count($op1) < count($op2)) {
  return -1; //$op1 < $op2
 } else if(count($op1) > count($op1)) {
  return 1; //$op1 > op2
 }
 foreach ($op1 as $key => $val) {
  if(!array_key_exists($key,$op2)) {
  return null;
  } else if ($val < $op2[$key]) {
  return -1;
  } else if ($val > $op2[$key]) {
  return 1;
  }
 }
 return 0;
 }
 $arr1 = array(1,2,3,4,5);
 $arr2 = array(1,2,3,4,5);
 $arr3 = array(2,3,4,5,6);
 $arr4 = array(0,1,2,3,4);
 var_dump(standard_array_compare($arr1,$arr2));
 echo "<br/>";
 var_dump(standard_array_compare($arr1,$arr3));
 echo "<br/>";
 var_dump(standard_array_compare($arr1,$arr4));
?>

Run results:


int(0)
int(-1)
int(1)

For more readers interested in PHP related content, please check the topics on this site: "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "php Common Functions and Skills Summary", "PHP Error and Exception Handling Methods Summary", "PHP Basic Syntax Introduction Course", "php Object-Oriented Programming Introduction Course", "php+mysql Database Operation Introduction Course" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: