Iterating Elements of Array without Loops
Last updated: 27.08.2025
Views: 445
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:
-
How to Remove the jQuery Migrate Script from WordPress
If your WordPress project uses jQuery, then by default, WordPress also loads the jQuery Migrate script along with it. In 99% of cases, you don’t actually need this script...
-
jQuery Accordion Plugin
An accordion is often used on websites. This element is popular and convenient at the same time. An accordion helps to structure content and save space. In my work, I oft...
-
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...
Leave a Reply