Logo

Programming-Idioms

History of Idiom 20 > diff from v60 to v61

Edit summary for version 61 by ancarda:
[PHP] Format code snippet to PSR-12

Version 60

2019-09-26, 21:34:46

Version 61

2019-09-27, 08:58:32

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Code
function search($x, $m)
{
  for ($j = 0; $j < count($m); $j++) {
    if (($i = array_search($x, $m[$j])) !== false) {
      return array($i, $j);
    }
  }

  return null;
}
Code
function search($x, array $m): ?array
{
    for ($j = 0; $j < count($m); $j++) {
        if (($i = array_search($x, $m[$j])) !== false) {
            return [$i, $j];
        }
    }

    return null;
}
Doc URL
http://php.net/manual/en/function.array-search.php
Doc URL
http://php.net/manual/en/function.array-search.php