@@ -709,23 +709,32 @@ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not
709
709
710
710
$ rowNumber = $ rowValue = false ;
711
711
foreach ($ lookup_array as $ rowKey => $ rowData ) {
712
+ // break if we have passed possible keys
712
713
if ((is_numeric ($ lookup_value ) && is_numeric ($ rowData [$ firstColumn ]) && ($ rowData [$ firstColumn ] > $ lookup_value )) ||
713
714
(!is_numeric ($ lookup_value ) && !is_numeric ($ rowData [$ firstColumn ]) && (strtolower ($ rowData [$ firstColumn ]) > strtolower ($ lookup_value )))) {
714
715
break ;
715
716
}
716
717
// remember the last key, but only if datatypes match
717
718
if ((is_numeric ($ lookup_value ) && is_numeric ($ rowData [$ firstColumn ])) ||
718
719
(!is_numeric ($ lookup_value ) && !is_numeric ($ rowData [$ firstColumn ]))) {
719
- $ rowNumber = $ rowKey ;
720
- $ rowValue = $ rowData [$ firstColumn ];
720
+ if ($ not_exact_match ) {
721
+ $ rowNumber = $ rowKey ;
722
+ $ rowValue = $ rowData [$ firstColumn ];
723
+
724
+ continue ;
725
+ } elseif ((strtolower ($ rowData [$ firstColumn ]) == strtolower ($ lookup_value ))
726
+ // Spreadsheets software returns first exact match,
727
+ // we have sorted and we might have broken key orders
728
+ // we want the first one (by its initial index)
729
+ && (($ rowNumber == false ) || ($ rowKey < $ rowNumber ))
730
+ ) {
731
+ $ rowNumber = $ rowKey ;
732
+ $ rowValue = $ rowData [$ firstColumn ];
733
+ }
721
734
}
722
735
}
723
736
724
737
if ($ rowNumber !== false ) {
725
- if ((!$ not_exact_match ) && ($ rowValue != $ lookup_value )) {
726
- // if an exact match is required, we have what we need to return an appropriate response
727
- return Functions::NA ();
728
- }
729
738
// otherwise return the appropriate value
730
739
return $ lookup_array [$ rowNumber ][$ returnColumn ];
731
740
}
0 commit comments