Search the blog

PHP allows you to mix indexed arrays and associative arrays together. The function below demonstrates how you can determine whether an element is indexed or associative.

// A mixed array
$array = ['indexed', 'foo' => 'bar', 'indexed'];

print_r($array);

/*
Array
(
    [0] => indexed
    [foo] => bar
    [1] => indexed
)
*/

foreach ($array as $key => $value) {

    if (is_int($key) === true) { // Use `(string) ctype_digit($key)` for a looser check

        echo 'indexed' . PHP_EOL; 

    } else {

        echo 'associative' . PHP_EOL; 

    }

}

/*
Output: 

indexed
associative
indexed
*/
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.