Reputation: 11
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() )?
Upvotes: 0
Views: 77
Reputation: 3866
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
Upvotes: 1
Reputation: 9001
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
Upvotes: 0