Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array is list? [duplicate]

Tags:

arrays

php

list

Possible Duplicate:
PHP Arrays: A good way to check if an array is associative or sequential?

Hello :)

I was wondering what is the shortest (best) way to check if an array is

a list: array('a', 'b', 'c')

or it's an associative array: array('a' => 'b', 'c' => 'd')

fyi: I need this to make a custom json_encode function

like image 925
Teneff Avatar asked Mar 25 '11 11:03

Teneff


People also ask

Does array list contain duplicates?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

How do you check if an array of objects has duplicate values in Javascript?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How can you tell if an array is unique?

One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.


1 Answers

function is_assoc($array){
    return array_values($array)!==$array;
}

Note that it will also return TRUE if array is indexed but contains holes or doesn't start with 0, or keys aren't ordered. I usually prefer using this function because it gives best possible performance. As an alternative for these cases I prefer this (just keep in mind that it's almost 4 times slower than above):

function is_assoc($array){
    return !ctype_digit( implode('', array_keys($array)) );
}

Using ksort() as Rinuwise commented is a bit slower.

like image 114
Slava Avatar answered Oct 04 '22 13:10

Slava