Differentiate a linked array from a regular array

Without changing the signatures of the function, I want the PHP function to behave differently if a linked array is specified instead of a regular array.

Note. . You can assume that arrays are homogeneous. For example, array(1,2,"foo" => "bar")it is not accepted and can be ignored.

function my_func(Array $foo){
  if (…) {
    echo "Found associated array";
  }
  else {
    echo "Found regular array";
  }
}


my_func(array("foo" => "bar", "hello" => "world"));
# => "Found associated array"

my_func(array(1,2,3,4));
# => "Found regular array"

Is this possible with PHP?

+3
source share
6 answers

Just check the type of any key:

function is_associative(array $a) {
    return is_string(key($a));
}

$a = array(1 => 0);
$a2 = array("a" => 0);

var_dump(is_associative($a)); //false
var_dump(is_associative($a2)); //true
+6
source

array_values, , ( , , , ):

if ($array === array_values($array)) {}

, :

function isAssociative(array $array) {
    $c = count($array);
    for ($i = 0; $i < $c; $i++) {
        if (!isset($array[$i])) {
            return true;
        }
    }
    return false;
}

, , , , .

: , :

if (isset($array[0])) {
    // Non-Associative
} else {
    // Associative
}

, . , ( , , )...

+2

, $foo , .

<?php

function my_func(array $foo) {
    if (!is_int(key($foo))) {
        echo 'Found associative array';
    } else {
        echo 'Found indexed array';
    }
}

?>
+2

Assume arrays are homogenous; no mixtures.: , ( ) .

0

This will be one way to do this by checking if there are any keys consisting of non-numeric values:

function my_func($arr) {
   $keys = array_keys($arr); // pull out all the keys into a new array
   $non_numeric = preg_grep('/\D/', $keys); // find any keys containing non-digits
   if (count($non_numeric) > 0) {
       return TRUE; // at least one non-numeric key, so it not a "straight" array
   } else {
       return FALSE: // all keys are numeric, so most likely a straight array
   }
}
0
source
function is_associative($array) {
  return count(array_keys($array)) != array_filter(array_keys($array), 'is_numeric');
}
0
source

Source: https://habr.com/ru/post/1759406/


All Articles