HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMajor

is_numeric_array() is missing

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
is_numeric_arraymissingstackoverflow

Problem

I found that in PHP (or I probably can't find it) a proper is_numeric_array($array) function is missing. So I created one. The problem is that I don't think it's great and I don't know how to improve it.

Any suggestion?

My first function

function is_numeric_array($array)
{
    $i = 0;
    foreach ($array as $a => $b) { if (is_int($a)) { ++$i; } }
    if (count($array) === $i) { return true; }
    else { return false; }
}

is_numeric_array(array(0,0,0,0,0)); // true
is_numeric_array(array('str' => 1, 'str2' => 2, 'str3' => 3)); // false


Example

As asked, I provide an example on how this could be any useful.

function is_numeric_array($array)
{
    # Code below
}

function someFunction($array)
{
    if (is_numeric_array($array))
    {
        $query = $array[0];
        $param = $array[1];
        $fetch = $array[2];
    }
    else
    {
        $query = $array['query'];
        $param = $array['param'];
        $fetch = $array['fetch'];
    }

    # Do your sql/pdo stuff here
}

# This use is the same of ...
someFunction(array(
    'PDO SQL STATEMENT', 
    array('param1' => 1, 'param2' => 2, 'param3' => 3),
    true
));

# ... this one.
someFunction(array(
    'query' => 'PDO SQL STATEMENT',
    'param' => array('param1' => 1, 'param2' => 2, 'param3' => 3),
    'fetch' => true
));

# To choose one form instead of the other is coder's decision
# Also I know it is useless but I was just wondering why anybody actually looked forward this function

Solution

Instead of using a counter to count the keys for which the condition is true, you could just return false as soon as you find a key which is not an int and return true if the loop reaches its end without finding such a key:

foreach ($array as $a => $b) {
    if (!is_int($a)) {
        return false;
    }
}
return true;


This has the benefit that it short-circuits (i.e. it stops iterating once it finds a key that is not an int) and gets rid of the counter.

Code Snippets

foreach ($array as $a => $b) {
    if (!is_int($a)) {
        return false;
    }
}
return true;

Context

StackExchange Code Review Q#201, answer score: 45

Revisions (0)

No revisions yet.