Iterating Elements of Array without Loops
Last updated: 27.08.2025
Views: 355
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:
-
Vue Accordion Component
A simple and lightweight Vue 3 accordion component plugin. Supports both global plugin registration and local component usage. Written in TypeScript. The accordion compon...
-
Countdown Timer in JavaScript
Countdown timers are commonly used on websites that promote products, services, or special offers. You can often see them on landing pages or in online stores, where they...
-
Caching Data to a File Using PHP
Sometimes it becomes necessary to limit the number of requests to an external data source, especially when the data does not change frequently. For example, this can be u...
Leave a Reply