0

I have a function geturls() that returns $urls as array

$urls[1] $urls[2] .....$urls[44]

However I don't know count of $urls (sometimes 44 45 77 ....)

And I want to make a loop for many times (44 in this case but could change)

So here is my script

function geturls($xml){
//my function
}

$urls = geturls($xml);
$counti = count($urls);

for ($i = 1; $i <= $counti; $i++) {
$modifiedurl = modify($urls[$i]);
echo $modifiedurl;
}

Is there a better way to do this (I'm sure there is a better way without using count() )?

2 Answers 2

1

You can walk through an arrays elements with the array map function.

$modifiedUrls = array_map('modify', $urls);

Just made a test about our answers.

<?php

$start = microtime(true);

$urls = range(1, 1000000);

function modify($url)
{
    return "modified_".$url;
}

$modified_urls = [];

foreach ($urls as $url) {
    $modified_urls[] = modify($url);
}

// $modified_urls = array_map('modify', $urls);

$end = microtime(true);

$time_elapsed_secs = $end - $start;

echo $time_elapsed_secs;
  • foreach: 0.202~ ms

  • array_map: 0.130~s ms

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Ozan, but which is better in term of memory your way or the way of BEn Pearl Kahan ?
A foreach loop is always faster than map, but I always felt like it's a bit cleaner.
False comment! Sorry about that. Updated answer.
0

Use foreach():

$modified_urls = []; //create new array for modified URLs

foreach($urls as $url){
    $modified_urls[] = modify($url); //modify this URL and add it to the array
}

print_r($modified_urls); //output the array

2 Comments

Thank you for this fast answer
Please see answer by Ozan Kurt, which one do you think is better in term of memory ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.