Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

php - Cleanest and fastest way to filter subarrays

I'm using an array and a for loop in PHP and it works well without any problem, but I want to improve the performance and speed of the script.

This is my script (PHP) :

$data=[1,2,3,4=>[1,2]];
for ($i=0; $i < count($data); $i++) {
    if(is_array($data[$i]){
        //do something
    }
}

As you can see it will check the whole array to detect if array has sub array or not and the thing which I want to know is - is there anyway to filter this array and send the filtered sub arrays to foreach? I mean just use elements which have a sub array, like $data[4] which has this sub array : [1,2] (which I'm currently checking by using is_array in if(is_array($data[$i]){).

If the array was like this: $data=[1,2,3,4,5,6,7,8,9,10=>[1,2],11,12,13,14,15=>[1,2]]; it would take more time to find only 2 useful elements (10 and 15) and others (1 to 9 and 11 to 14) are useless, I want to skip them before I use them on foreach.

I'm not looking for a way to do it manually inside my existing loop, I'm looking for a built-in function which would be optimized for speed and performance.

Thanks a lot.

question from:https://stackoverflow.com/questions/66063772/cleanest-and-fastest-way-to-filter-subarrays

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Get all elements that is an array:

$data = array_filter($data, "is_array");

Get all elements that is not an array:

$data = array_filter($data, fn($e) => !is_array($e));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...