php

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"]
author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

Your email address will not be published. Required fields are marked *