Re: How to test that an array is 'indexed' vs 'associative'



On May 31, 6:57 am, Daniel Klein <dani...@xxxxxxxxxxxxxxxx> wrote:

I have a class constructor that accepts an array as the only
argument. The catch is that the array MUST be an 'integer-indexed'
array, not an 'associative' array, because the index position has
meaning.

It doesn't matter:

The indexed and associative array types are the same type in PHP

http://www.php.net/manual/en/language.types.array.php

Further, the index position has NOTHING do do with keys. Elements
are
stored in the order they were added, regardless of what keys they
were
assigned (unless, of course, keys were not assigned explicitly and
key
assignment was done by PHP). Try this:

$myWeirdArray = array(
3 => 'Element # 3 was added first',
2 => 'Element # 2 was added second',
1 => 'Element # 1 was added last'
);
var_dump($myWeirdArray);

How can I test for this in the constructor without having to
traverse the entire array and checking to make sure the keys
are numeric and sequential?

Don't. If the order is that important, you can just ignore the
keys.
Alternatively, you could always rethink your approach... :)

Cheers,
NC
.



Relevant Pages

  • Re: need to assign/edit values in multidimensional associative arrays
    ... assignment on an array within a foreach construct (or any construct, ... so normal foreach use and other iterations wouldn't impact ... >> I would like to iterate through this array and add an element to each ... >> design of PHP. ...
    (comp.lang.php)
  • Re: NEWBIE
    ... > I want to directly access the the individual values in an array by using ... > their keys. ... Can this be done in PHP? ...
    (comp.lang.php)
  • NEWBIE
    ... I want to directly access the the individual values in an array by using ... "Programming PHP" does not show how to do this. ... iterating through the array and processing keys, ...
    (comp.lang.php)
  • Re: NEWBIE
    ... > I want to directly access the the individual values in an array by using ... > their keys. ... Can this be done in PHP? ...
    (comp.lang.php)
  • Re: comparing some but not all fields in lists
    ... and what's in common." ... I should compare only 3 of the 82 fields in each list. ... comparing all 82 fields as a single array element. ... cannot handle multiple keys as you want it to. ...
    (perl.beginners)