function castArray($value)
{
return is_array($value) ? $value : [$value];
}
// Examples
castArray(1);
castArray([1, 2, 3]);
function isEmpty($arr)
{
return empty($arr);
}
// Examples
isEmpty([]); // true
isEmpty([1, 2, 3]); // false
function isEmpty($arr)
{
return !is_array($arr) || count($arr) === 0;
}
function isEmpty($arr)
{
return is_array($arr) && count($arr) === 0;
}
function isEmpty(array $arr)
{
return count($arr) === 0;
}
function cloneArray($array)
{
return $array;
}
// Usage (lol)
$clonedArray = cloneArray([231]); // [231]
function isEqual($arrayA, $arrayB)
{
return $arrayA === $arrayB;
}
// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
function isEqual($arrayA, $arrayB)
{
sort($arrayA);
sort($arrayB);
return $arrayA === $arrayB;
}
// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 3, 2]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
function toObject($arrayOfObjects, $key)
{
$object = [];
foreach ($arrayOfObjects as $subObject) {
$object[$subObject[$key]] = $subObject;
}
return $object;
}
// Example
$result = toObject(
[
[ "id" => '1', "name" => 'Alpha', "gender" => 'Male' ],
[ "id" => '2', "name" => 'Bravo', "gender" => 'Male' ],
[ "id" => '3', "name" => 'Charlie', "gender" => 'Female' ],
],
'id'
);
/*
[
1 => ['id' => '0', 'name' => 'Alpha', 'gender' => 'Male',],
2 => ['id' => '2','name' => 'Bravo','gender' => 'Male',],
3 => ['id' => '3','name' => 'Charlie','gender' => 'Female',],
]
*/
function toNumbers($array)
{
return array_map(function($value) {
return (float) $value;
], $array);
}
// Example
toNumbers(['2', '3', '4']); // [2, 3, 4]
function countBy($array, $column)
{
$uniqValues = [];
foreach ($array as $subArray) {
if (!isset($uniqValues[$subArray[$column]])) {
$uniqValues[$subArray[$column]] = 0;
}
++$uniqValues[$subArray[$column]];
}
return $uniqValues;
}
// Example
countBy([
[ 'branch' => 'audi', 'model' => 'q8', 'year' => '2019' ],
[ 'branch' => 'audi', 'model' => 'rs7', 'year' => '2020' ],
[ 'branch' => 'ford', 'model' => 'mustang', 'year' => '2019' ],
[ 'branch' => 'ford', 'model' => 'explorer', 'year' => '2020' ],
[ 'branch' => 'bmw', 'model' => 'x7', 'year' => '2020' ],
], 'branch');
/*
array(3) {
["audi"] => int(2)
["ford"] => int(2)
["bmw"] => int(1)
}
*/
function countOccurrences($array, $value)
{
$occurences = 0;
foreach ($array as $element) {
$occurences += $element === $value ? 1 : 0;
}
return $occurences;
}
// Examples
countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3
function countOccurrences($array, $value)
{
$arrayCountValues = array_count_values($array);
$occurences = isset($arrayCountValues[$value]) ? $arrayCountValues[$value] : 0;
return $occurences;
}
// Examples
countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3
function countOccurrences($array) {
return array_count_values($array);
}
// Examples
countOccurrences([2, 1, 3, 3, 2, 3]); // [ 1 => 1, 2 => 2, 3=> 3 ]
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // [ 'a' => 3, 'b' => 2, 'c' => 1 ]
function accumulate($array)
{
$currentSum = 0;
$cumulativeArray = [];
foreach ($array as $element) {
$currentSum += $element;
$cumulativeArray[] = $currentSum;
}
return $cumulativeArray;
}
// Example
accumulate([1, 2, 3, 4]); // [1, 3, 6, 10]
// Example
range(5, 10); // [5, 6, 7, 8, 9, 10]
function cartesian($arrayA, $arrayB)
{
$products = [];
foreach ($arrayA as $elementA) {
foreach ($arrayB as $elementB) {
$products[] = [$elementA, $elementB];
}
}
return $products;
}
// Example
cartesian([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ]
$array = [];
function closest($array, $value)
{
sort($array);
$minDelta = null;
$previousElement = null;
foreach ($array as $element) {
$currentDelta = abs($element - $value);
if (is_null($minDelta)) {
$minDelta = $currentDelta;
} elseif ($currentDelta < $minDelta) {
$minDelta = $currentDelta;
} else {
// The current delta is growing, so the closest number is reached.
break;
}
$previousElement = $element;
}
return $previousElement;
}
// Example
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33
function lastIndex($array, $predicateFunction)
{
$reversedArray = array_reverse($array);
foreach ($reversedArray as $index => $element) {
if ($predicateFunction($element)) {
return count($array) - $index - 1;
}
}
return null;
}
// Example
lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], function($i) {
return $i % 2 === 1;
}); // 4
lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], function($i) {
return $i > 6;
}); // 5
function indexOfMax($array)
{
return array_search(max($array), $array);
}
// Examples
indexOfMax([1, 3, 9, 7, 5]); // 2
indexOfMax([1, 3, 7, 7, 5]); // 2
function indexOfMin($array)
{
return array_search(min($array), $array);
}
// Examples
indexOfMin([6, 4, 8, 2, 10]); // 3
indexOfMin([6, 4, 2, 2, 10]); // 2
function findLongest($array)
{
$longestValue = 0;
foreach($array as $element) {
$longestValue = max($longestValue, strlen($element));
}
return $longestValue;
}
// Example
findLongest(['always','look','on','the','bright','side','of','life']); // 6
function maxBy($array, $column)
{
$maxValue = null;
$maxElement = null;
foreach ($array as $key => $element)
{
$elementValue = $element[$column];
if (is_null($maxValue) || $maxValue < $elementValue) {
$maxValue = $elementValue;
$maxElement = $element;
}
}
return $maxElement;
}
// Example
$people = [
[ 'name' => 'Bar', 'age' => 24 ],
[ 'name' => 'Baz', 'age' => 32 ],
[ 'name' => 'Foo', 'age' => 42 ],
[ 'name' => 'Fuzz', 'age' => 36 ],
];
maxBy($people, 'age'); // { 'name' => 'Foo', 'age' => 42 }
function minBy($array, $column)
{
$minValue = null;
$minElement = null;
foreach ($array as $key => $element)
{
$elementValue = $element[$column];
if (is_null($minValue) || $minValue > $elementValue) {
$minValue = $elementValue;
$minElement = $element;
}
}
return $minElement;
}
// Example
$people = [
[ 'name' => 'Bar', 'age' => 24 ],
[ 'name' => 'Baz', 'age' => 32 ],
[ 'name' => 'Foo', 'age' => 42 ],
[ 'name' => 'Fuzz', 'age' => 36 ],
];
minBy($people, 'age'); // { 'name' => 'Bar', 'age' => 24 }
function flat($thing)
{
$flattenArray = [];
if (is_array($thing)) {
foreach ($thing as $element) {
$flattenArray = array_merge($flattenArray, flat($element));
}
} else {
$flattenArray[] = $thing;
}
return $flattenArray;
}
// Example
flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']
function getNthItems($array, $nth)
{
$items = [];
foreach ($array as $key => $element) {
if ((($key+1) % $nth) === 0) {
$items[] = $element;
}
}
return $items;
}
// Examples
getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 2); // [2, 4, 6, 8]
getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 3); // [3, 6, 9]
function indices($array, $value)
{
$indices = [];
foreach ($array as $key => $element) {
if ($element === $value) {
$indices[] = $key;
}
}
return $indices;
}
// Examples
indices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3]
indices(['h', 'e', 'l', 'l', 'o'], 'w'); // []
function average($array)
{
if (empty($array)) {
return 0;
}
return array_sum($array) / count($array);
}
// Examples
average([1, 2, 3]); // 2
average([0, 10, 80]); // 30
function ranking($array)
{
$ranking = [];
$rsortArray = $array;
rsort($rsortArray);
foreach ($array as $value) {
foreach ($rsortArray as $rank => $rSortValue) {
if ($value === $rSortValue) {
$ranking[] = $rank + 1;
break;
}
}
}
return $ranking;
}
// Examples
ranking([80, 65, 90, 50]); // [2, 3, 1, 4]
ranking([80, 80, 70, 50]); // [1, 1, 3, 4]
ranking([80, 80, 80, 50]); // [1, 1, 1, 4]
function groupBy($array, $column)
{
$groupByArray = [];
foreach ($array as $element) {
$groupValue = $element[$column];
if (!isset($groupByArray[$groupValue])) {
$groupByArray[$groupValue] = [];
}
$groupByArray[$groupValue][] = $element;
}
return $groupByArray;
}
// Example
groupBy([
[ 'branch' => 'audi', 'model' => 'q8', 'year' => '2019' ],
[ 'branch' => 'audi', 'model' => 'rs7', 'year' => '2020' ],
[ 'branch' => 'ford', 'model' => 'mustang', 'year' => '2019' ],
[ 'branch' => 'ford', 'model' => 'explorer', 'year' => '2020' ],
[ 'branch' => 'bmw', 'model' => 'x7', 'year' => '2020' ],
], 'branch');
/*
[
audi: [
[ 'branch' => 'audi', 'model' => 'q8', 'year' => '2019' ],
[ 'branch' => 'audi', 'model' => 'rs7', 'year' => '2020' ]
],
bmw: [
[ 'branch' => 'bmw', 'model' => 'x7', 'year' => '2020' ]
],
ford: [
[ 'branch' => 'ford', 'model' => 'mustang', 'year' => '2019' ],
[ 'branch' => 'ford', 'model' => 'explorer', 'year' => '2020' ]
],
]
*/
function partition($array, $partitionFunction)
{
$partitionnedArray = [[],[]];
foreach ($array as $element) {
if ($partitionFunction($element)) {
$partitionnedArray[1][] = $element;
} else {
$partitionnedArray[0][] = $element;
}
}
return $partitionnedArray;
}
// Example
partition([1, 2, 3, 4, 5], function($n) {
return $n % 2;
});// [[2, 4], [1, 3, 5]]
Cette fonction supprime les lettres qui sont en doublons (différent donc du array_unique).
function removeDuplicate($array)
{
return array_keys(array_filter(array_count_values($array), function($value) {
return $value === 1;
}));
}
// Example
removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); // ['h', 'e', 'w', 'r', 'd']
function removeFalsy($array)
{
return array_filter($array, function($value) {
return !empty($value);
});
}
// Example
removeFalsy([0, 'a string', '', null, true, 5, 'other string', false]); // ['a string', true, 5, 'other string']
function sortBy($array, $column)
{
$sortedValues = [];
foreach ($array as $element) {
$sortedValues[] = $element[$column];
}
sort($sortedValues);
$sortByArray = [];
foreach ($sortedValues as $value) {
foreach ($array as $element) {
if($value === $element[$column]) {
$sortByArray[] = $element;
break;
}
}
}
return $sortByArray;
}
// Example
$people = [
[ 'name' => 'Foo', 'age' => 42 ],
[ 'name' => 'Bar', 'age' => 24 ],
[ 'name' => 'Fuzz', 'age' => 36 ],
[ 'name' => 'Baz', 'age' => 32 ],
];
sortBy($people, 'age');
/*
[
[ 'name' => 'Bar', 'age' => 24 ],
[ 'name' => 'Baz', 'age' => 32 ],
[ 'name' => 'Fuzz', 'age' => 36 ],
[ 'name' => 'Foo', 'age' => 42 ],
]
*/
function transpose($matrix)
{
$transposedMatrix = [];
for ($x = 0; $x < count($matrix) ; $x++) {
for ($y = 0; $y < count($matrix[0]) ; $y++) {
if (!isset($transposedMatrix[$x])) {
$transposedMatrix[$x] = [];
}
$transposedMatrix[$x][$y] = $matrix[$y][$x];
}
}
return $transposedMatrix;
}
// Example
transpose([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
/*
[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
]
*/
function swapItems($array, $firstItemKey, $secondItemKey)
{
$savedValue = $array[$firstItemKey];
$array[$firstItemKey] = $array[$secondItemKey];
$array[$secondItemKey] = $savedValue;
return $array;
}
// Example
swapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2]
function unzip($arrayOfArrays)
{
$unzippedArray = [];
foreach ($arrayOfArrays as $subArray) {
foreach ($subArray as $key => $value) {
if(!isset($unzippedArray[$key])) {
$unzippedArray[$key] = [];
}
$unzippedArray[$key][] = $value;
}
}
return $unzippedArray;
}
// Example
unzip([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]]
function zip()
{
$zippedArray = [];
$arraysToZip = func_get_args();
for ($i = 0; $i < count($arraysToZip[0]) ; $i++) {
if (!isset($zippedArray[$i])) {
$zippedArray[$i] = [];
}
foreach ($arraysToZip as $arrayToZip) {
$zippedArray[$i][] = $arrayToZip[$i];
}
}
return $zippedArray;
}
// Example
zip(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]); // [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
function diffDays($date, $otherDate)
{
$dateDiff = $date->diff($otherDate);
return $dateDiff->days;
}
// Example
diffDays(new \DateTime('2014-12-19'), new \DateTime('2020-01-01')); // 1839
function monthDiff($date, $otherDate)
{
$dateDiff = $date->diff($otherDate);
return (12 * $dateDiff->y) + $dateDiff->m;
}
// Example
monthDiff(new \DateTime('2014-12-19'), new \DateTime('2020-01-01')); // 153
monthDiff(new \DateTime('2020-01-01'), new \DateTime('2021-01-01')); // 12
function compare($a, $b)
{
return $a > $b;
}
// Example
compare(new \DateTime('2020-03-30'), new \DateTime('2020-01-01')); // true
Rien de plus simple avec une instance de DateTime, car format existe déjà.
function formatYmd($date)
{
return $date->format('Y-m-d');
}
// Example
formatYmd(new \DateTime()); // YYYY-MM-DD
function formatSeconds($s)
{
$dateTime = new \DateTime('2020-01-01');
$dateTime->modify('+'.$s.' SECOND');
return $dateTime->format('H:i:s');
}
// Examples
formatSeconds(200); // 00:03:20
formatSeconds(500); // 00:08:20
function extractDateValues(\DateTime $date)
{
return array(
$date->format('Y'),
$date->format('m'),
$date->format('d'),
$date->format('H'),
$date->format('i'),
$date->format('s'),
$date->format('u')
);
}
var_dump(extractDateValues(new \DateTime('2021-05-23 09:45:41')));
/*
array(7) {
[0]=>
string(4) "2021"
[1]=>
string(2) "05"
[2]=>
string(2) "23"
[3]=>
string(2) "09"
[4]=>
string(2) "45"
[5]=>
string(2) "41"
[6]=>
string(6) "000000"
}
*/
function format($date, $locale)
{
switch($locale) {
case 'fr_FR':
case 'pt_BR':
return $date->format('d/m/Y');
case 'en_US':
return $date->format('m/d/Y');
}
}
// Examples
var_dump(format(new \DateTime('2020-12-11'), 'fr_FR')); // string(10) "11/12/2020"
var_dump(format(new \DateTime('2020-12-11'), 'en_US')); // string(10) "12/11/2020"
function dayOfYear($date)
{
return $date->format('z');
}
// Example
var_dump(dayOfYear(new \DateTime('2020-04-16'))); // string(3) "106"
function getMonthName($date)
{
return $date->format('F');
}
// Example
var_dump(getMonthName(new \DateTime('2020-04-16'))); // string(3) "April"
function daysInMonth($month, $year)
{
$dateTime = new \DateTime($year.'-'.$month.'-'.'01');
return $dateTime->format('t');
}
// Examples
var_dump(daysInMonth(2, 2021)); // string(2) "28"
var_dump(daysInMonth(2, 2016)); // string(2) "29"
var_dump(daysInMonth(12, 2016)); // string(2) "31"
function tomorrow()
{
$dateTime = new \DateTime('tomorrow');
return $dateTime;
}
function getWeekday($date)
{
return $date->format('l');
}
var_dump(getWeekday(new \DateTime('2021-12-11'))); // string(8) "Saturday"
function yesterday()
{
$dateTime = new \DateTime('yesterday');
return $dateTime;
}
function sortDescending($arr)
{
rsort($arr); // $arr is passed to the function by reference.
return $arr;
}
// Example
sortDescending(array(new \DateTime('2019-01-12'), new \DateTime('2011-04-23'), new \DateTime('2017-05-01')));
function sortAscending($arr)
{
sort($arr); // $arr is passed to the function by reference.
return $arr;
}
// Example
sortAscending(array(new \DateTime('2019-01-12'), new \DateTime('2011-04-23'), new \DateTime('2017-05-01')));
function suffixAmPm($hour)
{
$dateTime = new \DateTime();
$dateTime->setTime($hour, 0);
return $dateTime->format('ga');
}
// Examples
var_dump(suffixAmPm(0)); // string(4) "12am"
var_dump(suffixAmPm(5)); // string(3) "5am"
var_dump(suffixAmPm(12)); // string(4) "12pm"
var_dump(suffixAmPm(15)); // string(3) "3pm"
var_dump(suffixAmPm(23)); // string(4) "11pm"
function getFirstDate($d)
{
$firstDateTime = new \DateTime($d->format('Y').'-'.$d->format('m').'-01');
return $firstDateTime;
}
// Example
var_dump(getFirstDate(new \DateTime('2020-12-11'))); //[...]"2020-12-01 00:00:00.000000"[/...]
function getLastDate($d)
{
$lastDateTime = new \DateTime($d->format('Y').'-'.$d->format('m').'-'.$d->format('t'));
return $lastDateTime;
}
// Example
var_dump(getLastDate(new \DateTime('2020-12-11'))); //[...]"2020-12-31 00:00:00.000000"[/...]
function getTimezone()
{
$dateTime = new \DateTime();
$dateTimeZone = $dateTime->getTimezone();
return $dateTimeZone->getName();
}
// Example
var_dump(getTimezone()); // string(13) "Europe/Berlin"
function getQuarter($d)
{
return intval(ceil($d->format('m')/3));
}
// Example
var_dump(getQuarter(new \DateTime('2021-12-04'))); // int(4)
var_dump(getQuarter(new \DateTime('2021-02-04'))); // int(1)
function numberOfDays($year)
{
$lastDay = new \DateTime($year.'-12-31');
return $lastDay->format('z');
}
//Examples
var_dump(numberOfDays(2021)); // string(3) "364"
var_dump(numberOfDays(2016)); // string(3) "365"
function midnightOfToday()
{
$clonedDate = new \DateTime();
$clonedDate->setTime(0, 0);
return $clonedDate;
}
// Example
var_dump(midnightOfToday()); // object(DateTime)#1 (3) {[...] string(26) "2021-05-23 00:00:00.000000"[/...]}