2
$value = array( '1' );
$value = array( '0' => '1' );

These are the two possible formats of arrays that will be passed to the function below. The first is for lists of items (1, 2, 3...) and second indicates a span (1 - 50). With those values, the function worked fine. But not if the span array is from 0 to X as shown above.

There are countless instances of both array types all over the place. This is the relevant part of the function that handles them

if ( is_array( $value ) )
{
    if ( $value[0] || $value[0] === '0' )
    {
        echo 'item array';
    }
    else
    {
        echo 'span array';
    }
}

I have tried these answers: How to check if PHP array is associative or sequential?

Which also work where the above function does, but cannot seem to differentiate between the arrays shown above.

This topic explains most of whats going on: A numeric string as array key in PHP

Am I unable to differentiate between the two arrays within the code provided? What am I not getting here?

Community
  • 1
  • 1
John Smith
  • 490
  • 2
  • 11

1 Answers1

1

The accepted answer of the linked question already answers yours:

A numeric string as array key in PHP

This is the important sentence:

If a key is the standard representation of an integer, it will be interpreted as such

That means

array( '1' )

is equal to

array( 0 => '1' ) 

is equal to

array( '0' => '1' );

The solution to your problem is to restructure your code:

  1. Do not use the same variable for different purposes
  2. Do not squeeze everything into arrays

If I understand your "span" data structure correctly, it is something like array('0' => 1, '1' => 50) to represent "1-50". Then I would recommend to refactor it into a simple value object:

class Span
{
    private $from, $to;
    public function __construct($from, $to)
    {
        $this->from = $from;
        $this->to = $to;
    }
    public static function fromArray(array $array)
    {
        return new self($array[0], $array[1]);
    }
    public function getFrom() 
    {
        return $this->from;
    }
    public function getTo() 
    {
        return $this->to;
    }
}
Community
  • 1
  • 1
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111