Iterating Elements of Array without Loops
Last updated: 27.08.2025
Views: 340
The examples are very abstract because there are cycles. Our condition will be as follows. It is necessary to select all elements of the array by a given attribute. Or, to put it more precisely, it is necessary to filter the array. There are several solutions.
The most suitable option in PHP is to use the built-in function array_filter(). Let’s imagine that it does not exist either. We write it using recursion.
On PHP, the function looks like this:
PHP
function getArrayElements($arr, $pattern) {
static $i = 0;
static $arrayResult = [];
if (preg_match($pattern, $arr[$i])) {
$arrayResult[] = $arr[$i];
}
$i++;
if (count($arr) == $i) {
return;
} else {
getArrayElements($arr, $pattern);
}
return $arrayResult;
}
Example:
PHP
$arr = ['a', 'xd', 'w', 1, 'y', 'x']; $pattern = '/^x/'; print_r(getArrayElements($arr, $pattern)); // Array ( [0] => xd [1] => x )
Now let’s look at the same thing in JavaScript. In JS, an array has a similar filter() method. Let’s try to do without it, use recursion
JavaScript
let i = 0,
arrayResult = [];
function getArrayElements(arr, pattern) {
if (pattern.test(arr[i])) {
arrayResult.push(arr[i]);
}
i++;
if (arr.length == i) {
return;
} else {
getArrayElements(arr, pattern);
}
return arrayResult;
}
Example:
JavaScript
const arr = ['a', 'xd', 'w', 1, 'y', 'x'],
pattern = /^x/;
console.log(getArrayElements(arr, pattern)); //["xd", "x"]
Similar posts:
-
Working with Cookies in JavaScript
Сookie (web cookie or browser cookie) is a string of information that can be stored in a browser and sent to the server. The maximum size for one cookie is 4096 bytes. T...
-
How to Remove the "Website" Field from the WordPress Comment Form
By default, WordPress includes a "Website" or "URL" field in its comment form. While this may be useful in some cases, it often attracts spammers who leave low-quality co...
-
Finding the Distance Between Two Points on a Map Using JavaScript (TypeScript)
If you have the coordinates of two points on a map, calculating the distance between them is a fairly straightforward task. This type of calculation is commonly used in m...
Leave a Reply