Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Created August 21, 2012 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/321ad9b4b8c4e1713488 to your computer and use it in GitHub Desktop.
Save mindplay-dk/321ad9b4b8c4e1713488 to your computer and use it in GitHub Desktop.
set-semantics for the array-type in PHP

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().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment