PHP and Arrays?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
How can one tell if a PHP array  is a simple array or a hashed array
(key/valye).  The gettype returns "array", but is there a function
that will tell me the type?

Also, when you have a mixed array, some flat, some hashed, how can you
tell the type of each element?

Re: PHP and Arrays?

David said the following on 15/09/2005 23:41:
Quoted text here. Click to load it

Not really, PHP does not distinguish between the two.

Even the numeric "array" is really implemented as a hash-map, as the  
indices do not have to be consecutive.


Re: PHP and Arrays?

Oli is correct, although you can probably "cheat" with something like

function array_is_simple(&$arr) {
        return false;

    $keys = array_keys($arr);
    foreach($keys as $x)
        if(!is_numeric($x) || intval($x) != $x)
            return false;    
    return true;

Re: PHP and Arrays?

ZeldorBlat wrote:
Quoted text here. Click to load it

   As Oli pointed out, this will only let you cheat half way.  Is this a  
"simple array" or a "hash":

array (0 => "foo",
        1 => "bar",
        3 => "good question");

   The function above returns true, but I would rather call it a hash.

   Similarly, this will return true:

array (0 => "foo",
        1.1 => "bar);

   However, the indexing is more of a hash than index.

   You could further try to cheat by extending "array_is_simple" to  
check for consecutiveness and for non-int values, but what is this:

$array3 = array ("0" => "first elemement",
                  "1" => "second elemeent",
                  "2" => "third element");

   Array_is_simple will return true, but this is actually a hash.


Re: PHP and Arrays?


Quoted text here. Click to load it

I would prefer this:

function array_is_simple(&$arr)
     return $arr == array_values($arr);

Hero Wanders

Site Timeline