Skip to content

Instantly share code, notes, and snippets.

@pawjunior
Created December 25, 2022 06:35
Show Gist options
  • Save pawjunior/c17dd578709d57e1fb7dd8f51b675fab to your computer and use it in GitHub Desktop.
Save pawjunior/c17dd578709d57e1fb7dd8f51b675fab to your computer and use it in GitHub Desktop.
//Напишите программу PHP, чтобы получить все значения для данного ключа.
<?php
function pluck($items, $key)
{
return array_map( function($item) use ($key) {
return is_object($item) ? $item->$key : $item[$key];
}, $items);
}
print_r(pluck([
['product_id' => 'p100', 'name' => 'Компьютер'],
['product_id' => 'p200', 'name' => 'Ноутбук'],
], 'name'));
?>
//Напишите PHP-программу для создания нового массива с n элементами, удаленными слева.
<?php
function drop_from_left($items, $n = 1)
{
return array_slice($items, $n);
}
print_r(drop_from_left([1, 2, 3]));
print_r(drop_from_left([1, 2, 3, 4], 2));
?>
//Напишите программу PHP, чтобы проверить, начинается ли заданная строка с заданной подстроки.
<?php
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0;
}
print_r(startsWith('Hi, this is me', 'Hi'));
?>
//Напишите программу PHP, которая будет вызывать данную функцию только один раз
<?php
function once($function)
{
return function (...$args) use ($function) {
static $called = false;
if ($called) {
return;
}
$called = true;
return $function(...$args);
};
}
$add = function ($a, $b) {
return $a + $b;
};
$once = once($add);
var_dump($once(10, 5));
var_dump($once(20, 10));
?>
//Напишите программу PHP для глубокого выравнивания заданного массива.
<?php
function deep_flatten($items)
{
$result = [];
foreach ($items as $item) {
if (!is_array($item)) {
$result[] = $item;
} else {
$result = array_merge($result, deep_flatten($item));
}
}
return $result;
}
$result = deep_flatten([1, [2], [[3], 4], 5, 6]);
print_r($result);
?>
//Напишите программу PHP, чтобы получить последний элемент, для которого данная функция возвращает значение истинности
<?php
function find_Last($items, $func)
{
$filteredItems = array_filter($items, $func);
return array_pop($filteredItems);
}
echo find_Last([1, 2, 3, 4], function ($n) {
return ($n % 2) === 1;
});
echo "\n";
echo find_Last([1, 2, 3, 4], function ($n) {
return ($n % 2) === 0;
});
?>
//Напишите программу PHP для фильтрации коллекции с использованием заданного обратного вызова
<?php
function reject($items, $func)
{
return array_values(array_diff($items, array_filter($items, $func)));
}
print_r(reject(['Green', 'Red', 'Black', 'White'], function ($item) {
return strlen($item) > 4;
}));
?>
//Напишите программу PHP, чтобы изменить исходный массив, чтобы отфильтровать указанные значения
<?php
function pull(&$items, ...$params)
{
$items = array_values(array_diff($items, $params));
return $items;
}
$items = ['a', 'b', 'c', 'a', 'b', 'c'];
print_r(pull($items, 'a', 'c'));
?>
//Напишите PHP-программу для карри функции, которая принимает аргументы в нескольких вызовах
<?php
function curry($function)
{
$accumulator = function ($arguments) use ($function, &$accumulator) {
return function (...$args) use ($function, $arguments, $accumulator) {
$arguments = array_merge($arguments, $args);
$reflection = new ReflectionFunction($function);
$totalArguments = $reflection->getNumberOfRequiredParameters();
if ($totalArguments <= count($arguments)) {
return $function(...$arguments);
}
return $accumulator($arguments);
};
};
return $accumulator([]);
}
$curriedAdd = curry(
function ($a, $b) {
return $a + $b;
}
);
$add10 = $curriedAdd(10);
var_dump($add10(15)); // 25
?>
//Напишите PHP-программу для создания функции, которая возвращает true для всех элементов массива, в противном случае - false
<?php
function test_all($items, $my_func)
{
if (count(array_filter($items, $my_func)) === count($items))
return 1;
else
return 0;
}
echo test_all([2, 3, 4, 5], function ($item) {return $item > 0;});
echo "\n";
echo test_all([-2, -3, -4, -5], function ($item) {return $item > 0;});
echo "\n";
echo test_all([-2, 3, 4, -5], function ($item) {return $item > 0;});
?>
//Напишите программу PHP, которая возвращает все элементы в данном массиве, кроме первого
<?php
function tail($items)
{
return count($items) > 1 ? array_slice($items, 1) : $items;
}
print_r(tail([1, 2, 3]));
?>
//Напишите программу PHP для сортировки набора данных массивов или объектов по ключу
<?php
function orderBy($items, $attr, $order)
{
$sortedItems = [];
foreach ($items as $item) {
$key = is_object($item) ? $item->{$attr} : $item[$attr];
$sortedItems[$key] = $item;
}
if ($order ==='desc') {
krsort($sortedItems);
} else {
ksort($sortedItems);
}
return array_values($sortedItems);
}
print_r(orderBy(
[
['id' => 2, 'name' => 'Red'],
['id' => 3, 'name' => 'Black'],
['id' => 1, 'name' => 'Green']
],
'id',
'desc'
));
?>
//Напишите программу PHP, чтобы проверить, равны ли два числа друг другу
<?php
function approximatelyEqual($number1, $number2, $epsilon = 0.001)
{
if (abs($number1 - $number2) < $epsilon)
return 1;
else
return 0;
}
print_r(approximatelyEqual(10.0, 10.00001));
echo("\n");
print_r(approximatelyEqual(10.0, 10.01));
?>
//Напишите PHP-программу для создания новой функции, которая объединяет несколько функций в один вызываемый объект
<?php
function compose(...$functions)
{
return array_reduce(
$functions,
function ($carry, $function) {
return function ($x) use ($carry, $function) {
return $function($carry($x));
};
},
function ($x) {
return $x;
}
);
}
$compose = compose(
// add 2
function ($x) {
return $x + 2;
},
// multiply 4
function ($x) {
return $x * 4;
}
);
print_r($compose(2));
echo("\n");
print_r($compose(3));
?>
//Напишите программу PHP, чтобы получить последний элемент данного списка
<?php
function last($items)
{
return end($items);
}
print_r(last([1, 2, 3]));
echo "\n";
print_r(last([2, 1, 3, -4, 5, 1, 2]));
?>
//Напишите программу PHP, чтобы получить заголовок заданного списка
<?php
function head($items)
{
return reset($items);
}
print_r(head([1, 2, 3]));
echo "\n";
print_r(head([2, 1, 3, -4, 5, 1, 2]));
?>
//Напишите программу PHP, чтобы получить массив с n элементами, удаленными из начала данного массива
<?php
function take($items, $n = 1)
{
return array_slice($items, 0, $n);
}
print_r(take([1, 2, 3], 1));
echo "\n";
print_r(take([1, 2, 3, 4, 5], 2));
?>
//Напишите программу PHP для фильтрации элементов данного массива, имеющих одно из указанных значений
<?php
function without($items, ...$params)
{
return array_values(array_diff($items, $params));
}
print_r(without([2, 1, 2, 3], 1, 2));
?>
//Напишите программу PHP для декапитализации первой буквы строки, а затем добавьте ее вместе с остальной частью строки
<?php
function decapitalize($string, $upperRest = false)
{
return lcfirst($upperRest ? strtoupper($string) : $string);
}
print_r(decapitalize('Python'));
?>
//Напишите PHP-программу для запоминания заданных функций в памяти
<?php
function memoize($func)
{
return function () use ($func) {
static $cache = [];
$args = func_get_args();
$key = serialize($args);
$cached = true;
if (!isset($cache[$key])) {
$cache[$key] = $func(...$args);
$cached = false;
}
return ['result' => $cache[$key], 'cached' => $cached];
};
}
$memoizedAdd = memoize(
function ($num) {
return $num + 10;
}
);
var_dump($memoizedAdd(5));
var_dump($memoizedAdd(6));
var_dump($memoizedAdd(5));
?>
//Напишите PHP-программу для группировки элементов массива на основе заданной функции
<?php
function groupBy($items, $func)
{
$group = [];
foreach ($items as $item) {
if ((!is_string($func) && is_callable($func)) || function_exists($func)) {
$key = call_user_func($func, $item);
$group[$key][] = $item;
} elseif (is_object($item)) {
$group[$item->{$func}][] = $item;
} elseif (isset($item[$func])) {
$group[$item[$func]][] = $item;
}
}
return $group;
}
print_r(groupBy(['one', 'two', 'three', 'four'], 'strlen'));
?>
//Напишите программу PHP, чтобы получить индекс последнего элемента, для которого данная функция возвращает значение истинности
<?php
function find_last_Index($items, $func)
{
$keys = array_keys(array_filter($items, $func));
return array_pop($keys);
}
echo find_last_Index([1, 2, 3, 4], function ($n) {
return ($n % 2) === 1;
});
echo "\n";
echo find_last_Index([1, 2, 3, 4], function ($n) {
return ($n % 2) === 0;
});
?>
//Напишите программу PHP для подсчета количества гласных в данной строке
<?php
function count_Vowels($string)
{
preg_match_all('/[aeiou]/i', $string, $matches);
return count($matches[0]);
}
print_r(count_Vowels('sampleInput'));
?>
//Напишите программу PHP, чтобы проверить плоский список на наличие дублирующихся значений. Возвращает true, если существуют повторяющиеся значения, и false, если все значения уникальны
<?php
function has_Duplicates($items)
{
if (count($items) > count(array_unique($items)))
return 1;
else
return 0;
}
print_r(has_Duplicates([1, 2, 3, 4, 5, 5]));
echo "\n";
print_r(has_Duplicates([1, 2, 3, 4, 5]));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment