On 2 May 2017 at 11:55, Rowan Collins <rowan.coll...@gmail.com> wrote:

> On 02/05/2017 10:13, Jesse Schalken wrote:
>
>> Related to the optimisation made by Sara Golemon here:
>> https://github.com/php/php-src/commit/c74bc87c74f48bc55541b3
>> bf2fc67d595f58a3b5
>>
>> I often define a function like this, which checks if an array is "vector
>> like" i.e. has keys 0,1,2..N:
>>
>> function is_vectorlike(array $a): bool {
>>    $i = 0;
>>    foreach ($a as $k => $v) {
>>      if ($k !== $i++) {
>>        return false;
>>      }
>>    }
>>    return true;
>> }
>>
>>
> +1, I've been thinking of making a similar suggestion. We can bikeshed the
> name (it should certainly start with "array_"), but I think there's a very
> good case for having an optimised implementation built in, given the
> opportunities for short-cutting based on representation details.
>
>
Wouldn't be better to introduce a new native type "vector"? I know it
sounds obnoxious introducing a new basic data type, but I think having a
workaround like is_vectorlike() wouldn't completely address the problem.

Other than serializations I also felt, many many times, the need to also
type-hint the input parameters with vector:

function do_something(array $a) {
  if (!is_vectorlike($a))
    throw new Exception("I don't like the input");
  // do something with $a
}

I feel like going back to the dark ages when I had to manually check for
is_string(), is_int() on the input parameters. Think how much better it
would be to be able to:

function do_something_ex(vector $a) {
  // do something with $a
}

Also it would be perfectly acceptable to implicitly cast a vector to an
array, since a vector is basically a packed array.

How does it sound? Complete madness?

  $a = [ "a", "b", "c" ];
  is_vector($a); // true
  is_array($a); // true
  unset($a[1]);
  is_vector($a); // false
  is_array($a); // true

Reply via email to