1

is there a command to know if an array has their keys as string or plain int?

Like:

$array1 = array('value1','value2','value3');
checkArr($array1); //> Returns true because there aren't keys as string

And:

$array2 = array('key1'=>'value1','key2'=>'value2','value3');
checkArr($array2); //> Returns false because there are keys as string

Note: I know I can parse all the array to check it.

1
  • Does it have to check for 0-based sequential index, or will 'any' int do? Commented Apr 3, 2011 at 17:51

4 Answers 4

1

The "compact" version to test this is:

$allnumeric =
array_sum(array_map("is_numeric", array_keys($array))) == count($array);

@Gumbo's suggestion is 1 letter shorter and could very well be a bit speedier for huge arrays:

count(array_filter(array_keys($array), "is_numeric")) == count($array);
Sign up to request clarification or add additional context in comments.

3 Comments

Better use array_filter instead of array_map and array_sum.
Good idea. One could exchange the array_sum() for another count() then probably.
@yes123: See edit. The params are just ordered a bit differently.
0

You can use array_keys to obtain the keys for the array and then analyse the resultant array.

Comments

0

look at array_keys() if values are int - you got ints if strings -> strings

Comments

0

If you want to check the array's keys, it would be probably better to use something like this:

reset($array);
while (($key = key($array)) !== null) {
    // check the key, for example:
    if (is_string($key)) {
        // ...
    }
    next($array);
}

This will be most performant, as there are no extraneous copies made of variables that you are not going to use.

On the other hand, this way is probably the most readable and makes the intent crystal clear:

$keys = array_keys($array);
foreach($keys as $key) {
    // check the key, for example:
    if (is_string($key)) {
        // ...
    }
}

Take your pick.

Important note:

Last time I checked, PHP would not let you have keys which are string representations of integers. For example:

$array = array();
$array["5"] = "foo";

echo $array[5]; // You might think this will not work, but it will

So keep that in mind when you are checking what the types of such keys are: they might have been created as strings, but PHP will have converted them to integers behind the scenes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.