views:

143

answers:

3

I have some code that may be passed either an indexed array of values, or an associative array of value pairs. (The parameter is then used to construct radio buttons.) What's the most elegant (least resource hungry?) method for determining which I have?

EDIT: One slight problem with this: what if the array to be tested is as follows....

$d = array(1,2,3,4,4,5);
unset($d[3]);

or even

array_unique($d);

Does this make $d an associative array?

{ I have:

<?php

$a = array(1,2,3,4);
$b = array('one'=>1,"Two"=>2,3=>"Three");
$c = array('one',"Two","Three");

function is_associative($array)
{
  $keys = array_keys($array);
  foreach ($keys as $key) {
    if(!is_int($key)) {
      return true;
    }
  }
  return false;
}

var_dump(is_associative($a));
var_dump(is_associative($b));
var_dump(is_associative($c));
?>

which seems cumbersome!}

+3  A: 

This has been covered on SO before.

From Greg's answer here:

function isAssoc($arr)
{
    return array_keys($arr) != range(0, count($arr) - 1);
}

Just for future reference, the comments section of the documentation page for the is_array() function also have lots of ideas for implementing an is_assoc() function.

Donut
This could be better, you're using 3 functions here whereas my implementation uses only 1.
Alix Axel
Slight problem - what if you're passed an array that's just had an element unset?
Dycey
Not covered precisely, given unsetting of an element (if you consider the result is still non-associative...)
Dycey
+1  A: 
function isAssoc($arr)
{
    return $arr !== array_values($arr);
}
Alix Axel
A: 

Thanks to Donut, there's a great solution on the is_array() page:

function is_assoc($var)
{
  return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

which handles uniqued or unset elements within an array.

Dycey