Skip to content

Instantly share code, notes, and snippets.

@joubertredrat
Last active January 22, 2019 20:41
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 joubertredrat/a1b63f5f0a5c253607823df7a2a5dbd3 to your computer and use it in GitHub Desktop.
Save joubertredrat/a1b63f5f0a5c253607823df7a2a5dbd3 to your computer and use it in GitHub Desktop.
PHP RFC: array_element_exists function

PHP RFC: array_element_exists

  • Version: 0.1
  • Date: 2019-01-22
  • Author:
  • Status: Concept
  • First Published at: Github gist

Introduction

Today, in_array just support if array contains elements, but isn't normalized into Array Functions. This RFC proposal new function normalized in Array Functions that count elements into array, that can used in both situations, check if element exists and count quantity of same element in array.

Proposal

New function array_element_exists, similar to in_array, but organized on Array Functions and with count elements.

Documentation

int|bool array_element_exists(mixed $var, array $array)

Count number of elements in array.

Parameters

var

The value to check.

array

An array with elements to check.

Return Values

Returns number of elements found in array, FALSE otherwise.

Examples

Example #1:

<?php
$array = array("a", "b", "c", "a", "b", "c", "a");

var_dump(array_element_exists("a", $array)); /// int(3)
var_dump(array_element_exists("b", $array)); // int(2)
var_dump(array_element_exists("d", $array)); // bool(false)

Backward Incompatible Changes

This RFC doesn't anything, this is new function.

Proposed PHP Version

The next PHP 7.x, current version 7.3.

RFC Impact

This RFC has no impact on existing core, functions or extensions.

Future Scope

Is out of scope, but can be considered depreciate in_array in the future.

Other observations

  • The name of function can be array_element_count instead array_element_exists.
  • The function can return only int, with zero with no elements or number of elements found.
<?php
require('polyfill.php');
$array = ['a', 'A', 'A', 'A', 'a', 't'];
var_dump(
array_element_exists('a', $array),
array_element_exists('x', $array)
);
<?php
if (!function_exists('array_element_exists')) {
function array_element_exists($item, array $array) {
if (!in_array($item, $array)) {
return false;
}
$count = 0;
foreach ($array as $value) {
if ($item === $value) {
$count++;
}
}
return $count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment