How to make an array loop faster in PHP

Is there any way to do this faster?

while ($item = current($data))
{
    echo '<ATTR>',$item, '</ATTR>', "\n";
    next($data);
}

I do not like that I need to create new variables, for example $ item.

0
source share
6 answers
<?php
$transport = array('foot', 'bike', 'car', 'plane');

foreach ($transport as $value) {
    echo $value;
}
?>
+4
source

If you do not want to create temporary variables, do the following:

while (current($data))
{
    echo '<ATTR>',current($data), '</ATTR>', "\n";
    next($data);
}

However, I do not know if this will really make it faster. They can only be said by the profiler, but this is such micro-optimization. I doubt you will notice the difference.

The best way to speed up the cycle is to use a faster computer.

+1
source

, , , implode.


if (count($data) > 0) {
     echo "<ATTR>".implode("</ATTR>\n<ATTR>", $data)."</ATTR>";
}
+1

$nl = "\n";

while ($item = current($data))
{
    echo '<ATTR>',$item, '</ATTR>',$nl;
    next($data);
}

, PHP, .

+1

foreach, . while().

foreach($data as $key => $value)
{
    echo $key . " => ".$value;
}

.

0

:

function my_func($str) {
    echo "<attr>{$str}</attr>\n";
}
array_map('my_func', $data);

( , foreach)

, PHP >= 5.3 (, , ), , -:

array_map(function ($item) {
    echo "<attr>{$item}</attr>\n";
}, $data);

, , .

0

Source: https://habr.com/ru/post/1713117/


All Articles