LookupRef.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Calculation;
  3. use PhpOffice\PhpSpreadsheet\Cell\Cell;
  4. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  5. use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
  6. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  7. class LookupRef
  8. {
  9. /**
  10. * CELL_ADDRESS.
  11. *
  12. * Creates a cell address as text, given specified row and column numbers.
  13. *
  14. * Excel Function:
  15. * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
  16. *
  17. * @param mixed $row Row number to use in the cell reference
  18. * @param mixed $column Column number to use in the cell reference
  19. * @param int $relativity Flag indicating the type of reference to return
  20. * 1 or omitted Absolute
  21. * 2 Absolute row; relative column
  22. * 3 Relative row; absolute column
  23. * 4 Relative
  24. * @param bool $referenceStyle A logical value that specifies the A1 or R1C1 reference style.
  25. * TRUE or omitted CELL_ADDRESS returns an A1-style reference
  26. * FALSE CELL_ADDRESS returns an R1C1-style reference
  27. * @param string $sheetText Optional Name of worksheet to use
  28. *
  29. * @return string
  30. */
  31. public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '')
  32. {
  33. $row = Functions::flattenSingleValue($row);
  34. $column = Functions::flattenSingleValue($column);
  35. $relativity = Functions::flattenSingleValue($relativity);
  36. $sheetText = Functions::flattenSingleValue($sheetText);
  37. if (($row < 1) || ($column < 1)) {
  38. return Functions::VALUE();
  39. }
  40. if ($sheetText > '') {
  41. if (strpos($sheetText, ' ') !== false) {
  42. $sheetText = "'" . $sheetText . "'";
  43. }
  44. $sheetText .= '!';
  45. }
  46. if ((!is_bool($referenceStyle)) || $referenceStyle) {
  47. $rowRelative = $columnRelative = '$';
  48. $column = Coordinate::stringFromColumnIndex($column);
  49. if (($relativity == 2) || ($relativity == 4)) {
  50. $columnRelative = '';
  51. }
  52. if (($relativity == 3) || ($relativity == 4)) {
  53. $rowRelative = '';
  54. }
  55. return $sheetText . $columnRelative . $column . $rowRelative . $row;
  56. }
  57. if (($relativity == 2) || ($relativity == 4)) {
  58. $column = '[' . $column . ']';
  59. }
  60. if (($relativity == 3) || ($relativity == 4)) {
  61. $row = '[' . $row . ']';
  62. }
  63. return $sheetText . 'R' . $row . 'C' . $column;
  64. }
  65. /**
  66. * COLUMN.
  67. *
  68. * Returns the column number of the given cell reference
  69. * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
  70. * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
  71. * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
  72. *
  73. * Excel Function:
  74. * =COLUMN([cellAddress])
  75. *
  76. * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers
  77. *
  78. * @return int|int[]
  79. */
  80. public static function COLUMN($cellAddress = null)
  81. {
  82. if ($cellAddress === null || trim($cellAddress) === '') {
  83. return 0;
  84. }
  85. if (is_array($cellAddress)) {
  86. foreach ($cellAddress as $columnKey => $value) {
  87. $columnKey = preg_replace('/[^a-z]/i', '', $columnKey);
  88. return (int) Coordinate::columnIndexFromString($columnKey);
  89. }
  90. } else {
  91. list($sheet, $cellAddress) = Worksheet::extractSheetTitle($cellAddress, true);
  92. if (strpos($cellAddress, ':') !== false) {
  93. list($startAddress, $endAddress) = explode(':', $cellAddress);
  94. $startAddress = preg_replace('/[^a-z]/i', '', $startAddress);
  95. $endAddress = preg_replace('/[^a-z]/i', '', $endAddress);
  96. $returnValue = [];
  97. do {
  98. $returnValue[] = (int) Coordinate::columnIndexFromString($startAddress);
  99. } while ($startAddress++ != $endAddress);
  100. return $returnValue;
  101. }
  102. $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress);
  103. return (int) Coordinate::columnIndexFromString($cellAddress);
  104. }
  105. }
  106. /**
  107. * COLUMNS.
  108. *
  109. * Returns the number of columns in an array or reference.
  110. *
  111. * Excel Function:
  112. * =COLUMNS(cellAddress)
  113. *
  114. * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
  115. *
  116. * @return int The number of columns in cellAddress
  117. */
  118. public static function COLUMNS($cellAddress = null)
  119. {
  120. if ($cellAddress === null || $cellAddress === '') {
  121. return 1;
  122. } elseif (!is_array($cellAddress)) {
  123. return Functions::VALUE();
  124. }
  125. reset($cellAddress);
  126. $isMatrix = (is_numeric(key($cellAddress)));
  127. list($columns, $rows) = Calculation::getMatrixDimensions($cellAddress);
  128. if ($isMatrix) {
  129. return $rows;
  130. }
  131. return $columns;
  132. }
  133. /**
  134. * ROW.
  135. *
  136. * Returns the row number of the given cell reference
  137. * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
  138. * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
  139. * reference of the cell in which the ROW function appears; otherwise this function returns 0.
  140. *
  141. * Excel Function:
  142. * =ROW([cellAddress])
  143. *
  144. * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers
  145. *
  146. * @return int or array of integer
  147. */
  148. public static function ROW($cellAddress = null)
  149. {
  150. if ($cellAddress === null || trim($cellAddress) === '') {
  151. return 0;
  152. }
  153. if (is_array($cellAddress)) {
  154. foreach ($cellAddress as $columnKey => $rowValue) {
  155. foreach ($rowValue as $rowKey => $cellValue) {
  156. return (int) preg_replace('/\D/', '', $rowKey);
  157. }
  158. }
  159. } else {
  160. list($sheet, $cellAddress) = Worksheet::extractSheetTitle($cellAddress, true);
  161. if (strpos($cellAddress, ':') !== false) {
  162. list($startAddress, $endAddress) = explode(':', $cellAddress);
  163. $startAddress = preg_replace('/\D/', '', $startAddress);
  164. $endAddress = preg_replace('/\D/', '', $endAddress);
  165. $returnValue = [];
  166. do {
  167. $returnValue[][] = (int) $startAddress;
  168. } while ($startAddress++ != $endAddress);
  169. return $returnValue;
  170. }
  171. list($cellAddress) = explode(':', $cellAddress);
  172. return (int) preg_replace('/\D/', '', $cellAddress);
  173. }
  174. }
  175. /**
  176. * ROWS.
  177. *
  178. * Returns the number of rows in an array or reference.
  179. *
  180. * Excel Function:
  181. * =ROWS(cellAddress)
  182. *
  183. * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
  184. *
  185. * @return int The number of rows in cellAddress
  186. */
  187. public static function ROWS($cellAddress = null)
  188. {
  189. if ($cellAddress === null || $cellAddress === '') {
  190. return 1;
  191. } elseif (!is_array($cellAddress)) {
  192. return Functions::VALUE();
  193. }
  194. reset($cellAddress);
  195. $isMatrix = (is_numeric(key($cellAddress)));
  196. list($columns, $rows) = Calculation::getMatrixDimensions($cellAddress);
  197. if ($isMatrix) {
  198. return $columns;
  199. }
  200. return $rows;
  201. }
  202. /**
  203. * HYPERLINK.
  204. *
  205. * Excel Function:
  206. * =HYPERLINK(linkURL,displayName)
  207. *
  208. * @category Logical Functions
  209. *
  210. * @param string $linkURL Value to check, is also the value returned when no error
  211. * @param string $displayName Value to return when testValue is an error condition
  212. * @param Cell $pCell The cell to set the hyperlink in
  213. *
  214. * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
  215. */
  216. public static function HYPERLINK($linkURL = '', $displayName = null, Cell $pCell = null)
  217. {
  218. $linkURL = ($linkURL === null) ? '' : Functions::flattenSingleValue($linkURL);
  219. $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName);
  220. if ((!is_object($pCell)) || (trim($linkURL) == '')) {
  221. return Functions::REF();
  222. }
  223. if ((is_object($displayName)) || trim($displayName) == '') {
  224. $displayName = $linkURL;
  225. }
  226. $pCell->getHyperlink()->setUrl($linkURL);
  227. $pCell->getHyperlink()->setTooltip($displayName);
  228. return $displayName;
  229. }
  230. /**
  231. * INDIRECT.
  232. *
  233. * Returns the reference specified by a text string.
  234. * References are immediately evaluated to display their contents.
  235. *
  236. * Excel Function:
  237. * =INDIRECT(cellAddress)
  238. *
  239. * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
  240. *
  241. * @param null|array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula)
  242. * @param Cell $pCell The current cell (containing this formula)
  243. *
  244. * @return mixed The cells referenced by cellAddress
  245. *
  246. * @todo Support for the optional a1 parameter introduced in Excel 2010
  247. */
  248. public static function INDIRECT($cellAddress = null, Cell $pCell = null)
  249. {
  250. $cellAddress = Functions::flattenSingleValue($cellAddress);
  251. if ($cellAddress === null || $cellAddress === '') {
  252. return Functions::REF();
  253. }
  254. $cellAddress1 = $cellAddress;
  255. $cellAddress2 = null;
  256. if (strpos($cellAddress, ':') !== false) {
  257. list($cellAddress1, $cellAddress2) = explode(':', $cellAddress);
  258. }
  259. if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress1, $matches)) ||
  260. (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress2, $matches)))) {
  261. if (!preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $cellAddress1, $matches)) {
  262. return Functions::REF();
  263. }
  264. if (strpos($cellAddress, '!') !== false) {
  265. list($sheetName, $cellAddress) = Worksheet::extractSheetTitle($cellAddress, true);
  266. $sheetName = trim($sheetName, "'");
  267. $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
  268. } else {
  269. $pSheet = $pCell->getWorksheet();
  270. }
  271. return Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false);
  272. }
  273. if (strpos($cellAddress, '!') !== false) {
  274. list($sheetName, $cellAddress) = Worksheet::extractSheetTitle($cellAddress, true);
  275. $sheetName = trim($sheetName, "'");
  276. $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
  277. } else {
  278. $pSheet = $pCell->getWorksheet();
  279. }
  280. return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
  281. }
  282. /**
  283. * OFFSET.
  284. *
  285. * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
  286. * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
  287. * the number of columns to be returned.
  288. *
  289. * Excel Function:
  290. * =OFFSET(cellAddress, rows, cols, [height], [width])
  291. *
  292. * @param null|string $cellAddress The reference from which you want to base the offset. Reference must refer to a cell or
  293. * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
  294. * @param mixed $rows The number of rows, up or down, that you want the upper-left cell to refer to.
  295. * Using 5 as the rows argument specifies that the upper-left cell in the reference is
  296. * five rows below reference. Rows can be positive (which means below the starting reference)
  297. * or negative (which means above the starting reference).
  298. * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell of the result
  299. * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
  300. * reference is five columns to the right of reference. Cols can be positive (which means
  301. * to the right of the starting reference) or negative (which means to the left of the
  302. * starting reference).
  303. * @param mixed $height The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
  304. * @param mixed $width The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
  305. * @param null|Cell $pCell
  306. *
  307. * @return string A reference to a cell or range of cells
  308. */
  309. public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, Cell $pCell = null)
  310. {
  311. $rows = Functions::flattenSingleValue($rows);
  312. $columns = Functions::flattenSingleValue($columns);
  313. $height = Functions::flattenSingleValue($height);
  314. $width = Functions::flattenSingleValue($width);
  315. if ($cellAddress === null) {
  316. return 0;
  317. }
  318. if (!is_object($pCell)) {
  319. return Functions::REF();
  320. }
  321. $sheetName = null;
  322. if (strpos($cellAddress, '!')) {
  323. list($sheetName, $cellAddress) = Worksheet::extractSheetTitle($cellAddress, true);
  324. $sheetName = trim($sheetName, "'");
  325. }
  326. if (strpos($cellAddress, ':')) {
  327. list($startCell, $endCell) = explode(':', $cellAddress);
  328. } else {
  329. $startCell = $endCell = $cellAddress;
  330. }
  331. list($startCellColumn, $startCellRow) = Coordinate::coordinateFromString($startCell);
  332. list($endCellColumn, $endCellRow) = Coordinate::coordinateFromString($endCell);
  333. $startCellRow += $rows;
  334. $startCellColumn = Coordinate::columnIndexFromString($startCellColumn) - 1;
  335. $startCellColumn += $columns;
  336. if (($startCellRow <= 0) || ($startCellColumn < 0)) {
  337. return Functions::REF();
  338. }
  339. $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1;
  340. if (($width != null) && (!is_object($width))) {
  341. $endCellColumn = $startCellColumn + $width - 1;
  342. } else {
  343. $endCellColumn += $columns;
  344. }
  345. $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1);
  346. if (($height != null) && (!is_object($height))) {
  347. $endCellRow = $startCellRow + $height - 1;
  348. } else {
  349. $endCellRow += $rows;
  350. }
  351. if (($endCellRow <= 0) || ($endCellColumn < 0)) {
  352. return Functions::REF();
  353. }
  354. $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1);
  355. $cellAddress = $startCellColumn . $startCellRow;
  356. if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
  357. $cellAddress .= ':' . $endCellColumn . $endCellRow;
  358. }
  359. if ($sheetName !== null) {
  360. $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
  361. } else {
  362. $pSheet = $pCell->getWorksheet();
  363. }
  364. return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
  365. }
  366. /**
  367. * CHOOSE.
  368. *
  369. * Uses lookup_value to return a value from the list of value arguments.
  370. * Use CHOOSE to select one of up to 254 values based on the lookup_value.
  371. *
  372. * Excel Function:
  373. * =CHOOSE(index_num, value1, [value2], ...)
  374. *
  375. * @param mixed $index_num Specifies which value argument is selected.
  376. * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
  377. * between 1 and 254.
  378. * @param mixed $value1 ... Value1 is required, subsequent values are optional.
  379. * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
  380. * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
  381. * text.
  382. *
  383. * @return mixed The selected value
  384. */
  385. public static function CHOOSE(...$chooseArgs)
  386. {
  387. $chosenEntry = Functions::flattenArray(array_shift($chooseArgs));
  388. $entryCount = count($chooseArgs) - 1;
  389. if (is_array($chosenEntry)) {
  390. $chosenEntry = array_shift($chosenEntry);
  391. }
  392. if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
  393. --$chosenEntry;
  394. } else {
  395. return Functions::VALUE();
  396. }
  397. $chosenEntry = floor($chosenEntry);
  398. if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) {
  399. return Functions::VALUE();
  400. }
  401. if (is_array($chooseArgs[$chosenEntry])) {
  402. return Functions::flattenArray($chooseArgs[$chosenEntry]);
  403. }
  404. return $chooseArgs[$chosenEntry];
  405. }
  406. /**
  407. * MATCH.
  408. *
  409. * The MATCH function searches for a specified item in a range of cells
  410. *
  411. * Excel Function:
  412. * =MATCH(lookup_value, lookup_array, [match_type])
  413. *
  414. * @param mixed $lookupValue The value that you want to match in lookup_array
  415. * @param mixed $lookupArray The range of cells being searched
  416. * @param mixed $matchType The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
  417. *
  418. * @return int The relative position of the found item
  419. */
  420. public static function MATCH($lookupValue, $lookupArray, $matchType = 1)
  421. {
  422. $lookupArray = Functions::flattenArray($lookupArray);
  423. $lookupValue = Functions::flattenSingleValue($lookupValue);
  424. $matchType = ($matchType === null) ? 1 : (int) Functions::flattenSingleValue($matchType);
  425. $initialLookupValue = $lookupValue;
  426. // MATCH is not case sensitive
  427. $lookupValue = StringHelper::strToLower($lookupValue);
  428. // Lookup_value type has to be number, text, or logical values
  429. if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) {
  430. return Functions::NA();
  431. }
  432. // Match_type is 0, 1 or -1
  433. if (($matchType !== 0) && ($matchType !== -1) && ($matchType !== 1)) {
  434. return Functions::NA();
  435. }
  436. // Lookup_array should not be empty
  437. $lookupArraySize = count($lookupArray);
  438. if ($lookupArraySize <= 0) {
  439. return Functions::NA();
  440. }
  441. // Lookup_array should contain only number, text, or logical values, or empty (null) cells
  442. foreach ($lookupArray as $i => $lookupArrayValue) {
  443. // check the type of the value
  444. if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
  445. (!is_bool($lookupArrayValue)) && ($lookupArrayValue !== null)
  446. ) {
  447. return Functions::NA();
  448. }
  449. // Convert strings to lowercase for case-insensitive testing
  450. if (is_string($lookupArrayValue)) {
  451. $lookupArray[$i] = StringHelper::strToLower($lookupArrayValue);
  452. }
  453. if (($lookupArrayValue === null) && (($matchType == 1) || ($matchType == -1))) {
  454. $lookupArray = array_slice($lookupArray, 0, $i - 1);
  455. }
  456. }
  457. if ($matchType == 1) {
  458. // If match_type is 1 the list has to be processed from last to first
  459. $lookupArray = array_reverse($lookupArray);
  460. $keySet = array_reverse(array_keys($lookupArray));
  461. }
  462. // **
  463. // find the match
  464. // **
  465. if ($matchType == 0 || $matchType == 1) {
  466. foreach ($lookupArray as $i => $lookupArrayValue) {
  467. $onlyNumeric = is_numeric($lookupArrayValue) && is_numeric($lookupValue);
  468. $onlyNumericExactMatch = $onlyNumeric && $lookupArrayValue == $lookupValue;
  469. $nonOnlyNumericExactMatch = !$onlyNumeric && $lookupArrayValue === $lookupValue;
  470. $exactMatch = $onlyNumericExactMatch || $nonOnlyNumericExactMatch;
  471. if (($matchType == 0) && $exactMatch) {
  472. // exact match
  473. return $i + 1;
  474. } elseif (($matchType == 1) && ($lookupArrayValue <= $lookupValue)) {
  475. $i = array_search($i, $keySet);
  476. // The current value is the (first) match
  477. return $i + 1;
  478. }
  479. }
  480. } else {
  481. // matchType = -1
  482. // "Special" case: since the array it's supposed to be ordered in descending order, the
  483. // Excel algorithm gives up immediately if the first element is smaller than the searched value
  484. if ($lookupArray[0] < $lookupValue) {
  485. return Functions::NA();
  486. }
  487. $maxValueKey = null;
  488. // The basic algorithm is:
  489. // Iterate and keep the highest match until the next element is smaller than the searched value.
  490. // Return immediately if perfect match is found
  491. foreach ($lookupArray as $i => $lookupArrayValue) {
  492. if ($lookupArrayValue == $lookupValue) {
  493. // Another "special" case. If a perfect match is found,
  494. // the algorithm gives up immediately
  495. return $i + 1;
  496. } elseif ($lookupArrayValue >= $lookupValue) {
  497. $maxValueKey = $i + 1;
  498. }
  499. }
  500. if ($maxValueKey !== null) {
  501. return $maxValueKey;
  502. }
  503. }
  504. // Unsuccessful in finding a match, return #N/A error value
  505. return Functions::NA();
  506. }
  507. /**
  508. * INDEX.
  509. *
  510. * Uses an index to choose a value from a reference or array
  511. *
  512. * Excel Function:
  513. * =INDEX(range_array, row_num, [column_num])
  514. *
  515. * @param mixed $arrayValues A range of cells or an array constant
  516. * @param mixed $rowNum The row in array from which to return a value. If row_num is omitted, column_num is required.
  517. * @param mixed $columnNum The column in array from which to return a value. If column_num is omitted, row_num is required.
  518. *
  519. * @return mixed the value of a specified cell or array of cells
  520. */
  521. public static function INDEX($arrayValues, $rowNum = 0, $columnNum = 0)
  522. {
  523. $rowNum = Functions::flattenSingleValue($rowNum);
  524. $columnNum = Functions::flattenSingleValue($columnNum);
  525. if (($rowNum < 0) || ($columnNum < 0)) {
  526. return Functions::VALUE();
  527. }
  528. if (!is_array($arrayValues) || ($rowNum > count($arrayValues))) {
  529. return Functions::REF();
  530. }
  531. $rowKeys = array_keys($arrayValues);
  532. $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
  533. if ($columnNum > count($columnKeys)) {
  534. return Functions::VALUE();
  535. } elseif ($columnNum == 0) {
  536. if ($rowNum == 0) {
  537. return $arrayValues;
  538. }
  539. $rowNum = $rowKeys[--$rowNum];
  540. $returnArray = [];
  541. foreach ($arrayValues as $arrayColumn) {
  542. if (is_array($arrayColumn)) {
  543. if (isset($arrayColumn[$rowNum])) {
  544. $returnArray[] = $arrayColumn[$rowNum];
  545. } else {
  546. return [$rowNum => $arrayValues[$rowNum]];
  547. }
  548. } else {
  549. return $arrayValues[$rowNum];
  550. }
  551. }
  552. return $returnArray;
  553. }
  554. $columnNum = $columnKeys[--$columnNum];
  555. if ($rowNum > count($rowKeys)) {
  556. return Functions::VALUE();
  557. } elseif ($rowNum == 0) {
  558. return $arrayValues[$columnNum];
  559. }
  560. $rowNum = $rowKeys[--$rowNum];
  561. return $arrayValues[$rowNum][$columnNum];
  562. }
  563. /**
  564. * TRANSPOSE.
  565. *
  566. * @param array $matrixData A matrix of values
  567. *
  568. * @return array
  569. *
  570. * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix
  571. */
  572. public static function TRANSPOSE($matrixData)
  573. {
  574. $returnMatrix = [];
  575. if (!is_array($matrixData)) {
  576. $matrixData = [[$matrixData]];
  577. }
  578. $column = 0;
  579. foreach ($matrixData as $matrixRow) {
  580. $row = 0;
  581. foreach ($matrixRow as $matrixCell) {
  582. $returnMatrix[$row][$column] = $matrixCell;
  583. ++$row;
  584. }
  585. ++$column;
  586. }
  587. return $returnMatrix;
  588. }
  589. private static function vlookupSort($a, $b)
  590. {
  591. reset($a);
  592. $firstColumn = key($a);
  593. $aLower = StringHelper::strToLower($a[$firstColumn]);
  594. $bLower = StringHelper::strToLower($b[$firstColumn]);
  595. if ($aLower == $bLower) {
  596. return 0;
  597. }
  598. return ($aLower < $bLower) ? -1 : 1;
  599. }
  600. /**
  601. * VLOOKUP
  602. * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
  603. *
  604. * @param mixed $lookup_value The value that you want to match in lookup_array
  605. * @param mixed $lookup_array The range of cells being searched
  606. * @param mixed $index_number The column number in table_array from which the matching value must be returned. The first column is 1.
  607. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value
  608. *
  609. * @return mixed The value of the found cell
  610. */
  611. public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
  612. {
  613. $lookup_value = Functions::flattenSingleValue($lookup_value);
  614. $index_number = Functions::flattenSingleValue($index_number);
  615. $not_exact_match = Functions::flattenSingleValue($not_exact_match);
  616. // index_number must be greater than or equal to 1
  617. if ($index_number < 1) {
  618. return Functions::VALUE();
  619. }
  620. // index_number must be less than or equal to the number of columns in lookup_array
  621. if ((!is_array($lookup_array)) || (empty($lookup_array))) {
  622. return Functions::REF();
  623. }
  624. $f = array_keys($lookup_array);
  625. $firstRow = array_pop($f);
  626. if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
  627. return Functions::REF();
  628. }
  629. $columnKeys = array_keys($lookup_array[$firstRow]);
  630. $returnColumn = $columnKeys[--$index_number];
  631. $firstColumn = array_shift($columnKeys);
  632. if (!$not_exact_match) {
  633. uasort($lookup_array, ['self', 'vlookupSort']);
  634. }
  635. $lookupLower = StringHelper::strToLower($lookup_value);
  636. $rowNumber = $rowValue = false;
  637. foreach ($lookup_array as $rowKey => $rowData) {
  638. $firstLower = StringHelper::strToLower($rowData[$firstColumn]);
  639. // break if we have passed possible keys
  640. if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
  641. (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && ($firstLower > $lookupLower))) {
  642. break;
  643. }
  644. // remember the last key, but only if datatypes match
  645. if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn])) ||
  646. (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]))) {
  647. if ($not_exact_match) {
  648. $rowNumber = $rowKey;
  649. continue;
  650. } elseif (($firstLower == $lookupLower)
  651. // Spreadsheets software returns first exact match,
  652. // we have sorted and we might have broken key orders
  653. // we want the first one (by its initial index)
  654. && (($rowNumber == false) || ($rowKey < $rowNumber))
  655. ) {
  656. $rowNumber = $rowKey;
  657. }
  658. }
  659. }
  660. if ($rowNumber !== false) {
  661. // return the appropriate value
  662. return $lookup_array[$rowNumber][$returnColumn];
  663. }
  664. return Functions::NA();
  665. }
  666. /**
  667. * HLOOKUP
  668. * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number.
  669. *
  670. * @param mixed $lookup_value The value that you want to match in lookup_array
  671. * @param mixed $lookup_array The range of cells being searched
  672. * @param mixed $index_number The row number in table_array from which the matching value must be returned. The first row is 1.
  673. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value
  674. *
  675. * @return mixed The value of the found cell
  676. */
  677. public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
  678. {
  679. $lookup_value = Functions::flattenSingleValue($lookup_value);
  680. $index_number = Functions::flattenSingleValue($index_number);
  681. $not_exact_match = Functions::flattenSingleValue($not_exact_match);
  682. // index_number must be greater than or equal to 1
  683. if ($index_number < 1) {
  684. return Functions::VALUE();
  685. }
  686. // index_number must be less than or equal to the number of columns in lookup_array
  687. if ((!is_array($lookup_array)) || (empty($lookup_array))) {
  688. return Functions::REF();
  689. }
  690. $f = array_keys($lookup_array);
  691. $firstRow = array_pop($f);
  692. if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array))) {
  693. return Functions::REF();
  694. }
  695. $firstkey = $f[0] - 1;
  696. $returnColumn = $firstkey + $index_number;
  697. $firstColumn = array_shift($f);
  698. $rowNumber = null;
  699. foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) {
  700. // break if we have passed possible keys
  701. $bothNumeric = is_numeric($lookup_value) && is_numeric($rowData);
  702. $bothNotNumeric = !is_numeric($lookup_value) && !is_numeric($rowData);
  703. $lookupLower = StringHelper::strToLower($lookup_value);
  704. $rowDataLower = StringHelper::strToLower($rowData);
  705. if (($bothNumeric && $rowData > $lookup_value) ||
  706. ($bothNotNumeric && $rowDataLower > $lookupLower)) {
  707. break;
  708. }
  709. // Remember the last key, but only if datatypes match (as in VLOOKUP)
  710. if ($bothNumeric || $bothNotNumeric) {
  711. if ($not_exact_match) {
  712. $rowNumber = $rowKey;
  713. continue;
  714. } elseif ($rowDataLower === $lookupLower
  715. && ($rowNumber === null || $rowKey < $rowNumber)
  716. ) {
  717. $rowNumber = $rowKey;
  718. }
  719. }
  720. }
  721. if ($rowNumber !== null) {
  722. // otherwise return the appropriate value
  723. return $lookup_array[$returnColumn][$rowNumber];
  724. }
  725. return Functions::NA();
  726. }
  727. /**
  728. * LOOKUP
  729. * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
  730. *
  731. * @param mixed $lookup_value The value that you want to match in lookup_array
  732. * @param mixed $lookup_vector The range of cells being searched
  733. * @param null|mixed $result_vector The column from which the matching value must be returned
  734. *
  735. * @return mixed The value of the found cell
  736. */
  737. public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null)
  738. {
  739. $lookup_value = Functions::flattenSingleValue($lookup_value);
  740. if (!is_array($lookup_vector)) {
  741. return Functions::NA();
  742. }
  743. $hasResultVector = isset($result_vector);
  744. $lookupRows = count($lookup_vector);
  745. $l = array_keys($lookup_vector);
  746. $l = array_shift($l);
  747. $lookupColumns = count($lookup_vector[$l]);
  748. // we correctly orient our results
  749. if (($lookupRows === 1 && $lookupColumns > 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) {
  750. $lookup_vector = self::TRANSPOSE($lookup_vector);
  751. $lookupRows = count($lookup_vector);
  752. $l = array_keys($lookup_vector);
  753. $lookupColumns = count($lookup_vector[array_shift($l)]);
  754. }
  755. if ($result_vector === null) {
  756. $result_vector = $lookup_vector;
  757. }
  758. $resultRows = count($result_vector);
  759. $l = array_keys($result_vector);
  760. $l = array_shift($l);
  761. $resultColumns = count($result_vector[$l]);
  762. // we correctly orient our results
  763. if ($resultRows === 1 && $resultColumns > 1) {
  764. $result_vector = self::TRANSPOSE($result_vector);
  765. $resultRows = count($result_vector);
  766. $r = array_keys($result_vector);
  767. $resultColumns = count($result_vector[array_shift($r)]);
  768. }
  769. if ($lookupRows === 2 && !$hasResultVector) {
  770. $result_vector = array_pop($lookup_vector);
  771. $lookup_vector = array_shift($lookup_vector);
  772. }
  773. if ($lookupColumns !== 2) {
  774. foreach ($lookup_vector as &$value) {
  775. if (is_array($value)) {
  776. $k = array_keys($value);
  777. $key1 = $key2 = array_shift($k);
  778. ++$key2;
  779. $dataValue1 = $value[$key1];
  780. } else {
  781. $key1 = 0;
  782. $key2 = 1;
  783. $dataValue1 = $value;
  784. }
  785. $dataValue2 = array_shift($result_vector);
  786. if (is_array($dataValue2)) {
  787. $dataValue2 = array_shift($dataValue2);
  788. }
  789. $value = [$key1 => $dataValue1, $key2 => $dataValue2];
  790. }
  791. unset($value);
  792. }
  793. return self::VLOOKUP($lookup_value, $lookup_vector, 2);
  794. }
  795. /**
  796. * FORMULATEXT.
  797. *
  798. * @param mixed $cellReference The cell to check
  799. * @param Cell $pCell The current cell (containing this formula)
  800. *
  801. * @return string
  802. */
  803. public static function FORMULATEXT($cellReference = '', Cell $pCell = null)
  804. {
  805. if ($pCell === null) {
  806. return Functions::REF();
  807. }
  808. preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches);
  809. $cellReference = $matches[6] . $matches[7];
  810. $worksheetName = trim($matches[3], "'");
  811. $worksheet = (!empty($worksheetName))
  812. ? $pCell->getWorksheet()->getParent()->getSheetByName($worksheetName)
  813. : $pCell->getWorksheet();
  814. if (!$worksheet->getCell($cellReference)->isFormula()) {
  815. return Functions::NA();
  816. }
  817. return $worksheet->getCell($cellReference)->getValue();
  818. }
  819. }