secret
Created

set-semantics for the array-type in PHP

  • Download Gist
gistfile1.md
Markdown

This RFC proposes the addition of a set of two new functions that simplify working with arrays containing a set of unique values or objects that do not have any natural (or distinct) scalar keys that can be used as indices.

While the array-type in PHP does not support set-semantics, these functions simplify working with a set of unique values or objects stored in an array.

array_delete()

The first function simplifies removal of a value from an array, when the index is not known:

array_delete(&$array, $value, $strict=true) : bool

The function is "destructive", in the sense that it modifies the array in-place - for non-destructive removal, use array_filter().

The boolean return-value indicates whether or not the specified value was present and was removed.

To clarify how this function works, here is the PHP equivalent function:

function array_delete(&$array, $value, $strict=true) {
  while (false !== ($index = array_search($value, $array, $strict))) {
    unset($array[$index]);
  }
}

If the same value occurs more than once in the given array, all occurrences of the given value will be deleted.

To prevent accidental deletion, $strict defaults to true - note that this differs from array_search() where the most likely objective is to "find something".

array_add()

To complement the array_delete() function, in terms of working with a set of unique values, a second function is proposed:

array_add(&$array, $value, $strict=true) : bool

This function is "destructive", like it's counterpart - for non-destructive addition, use array_merge().

The boolean return-value indicates whether or not the specified value was not already present and was added.

To clarify how this function works, here is the PHP equivalent function:

function array_add(&$array, $value, $strict=true) {
  if (false === array_search($value, $array, $strict)) {
    $array[] = $value;
    return true;
  }
  return false;
}

To prevent accidentally adding duplicates, $strict defaults to true - this is consistent with array_delete().

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.