← All examples

Linear search

PHP Algorithms

loop + return index

Flowchart (ISO 5807)

YesNoStartInput a, keyi = 0, count(a) - 1, 1a[i] === keyReturn iEndReturn -1EndFigure 1 — indexOf

Source code

function indexOf($a, $key) {
    for ($i = 0; $i < count($a); $i++) {
        if ($a[$i] === $key) {
            return $i;
        }
    }
    return -1;
}