This question already has answers here:
FOR loop performance in PHP
(6 answers)
Closed 8 years ago.
What is more efficient for the following loop operation in PHP:
$k = count($array);
for ($i = 0; $i < $k; $i++)
{
echo $array[$i];
}
Or
for ($i = 0; $i < count($array); $i++)
{
echo $array[$i];
}
I know that in JavaScript there is something like this possible and more efficient:
for (i = 0, j = array.length; i < j; i++)
{
console.log(array[i]);
}
This one is more efficient than 2nd one
<?php
$k = count($array);
for($i = 0; $i < $k; $i++)
{
echo $array[$i];
}
?>
thanks.
In this specific case your first example is faster, simply because to evaluate the condition $i < count($array) PHP will execute count() after every loop. So following that logic it would be faster to use a variable in your condition, rather than a function.
The more practical approach would be to use foreach() as mentioned elsewhere.
The first one is more efficient, the second one is calling the function count() each iteration.
I would use a foreach in this context.
From the PHP Docs..
The foreach construct provides an easy way to iterate over arrays.
Why foreach is efficient in this case ?
Definitely faster since you won't be calling a count() for determining the length of the array as you did above.
You can even access the keys of the arrays.
Lets test and see.
$array = array();
$array = array_pad($array, 1000, 0);
$iters = 1e4;
$tic = microtime(true);
for ($jj = 0; $jj < $iters; $jj++) {
$k = count($array);
for($i = 0; $i < $k; $i++) {
$vv = $array[$i];
}
}
$toc = microtime(true);
$time = $toc - $tic;
echo "Time for external \$k..: $time\n";
$tic = microtime(true);
for ($jj = 0; $jj < $iters; $jj++) {
for($i = 0; $i < count($array); $i++) {
$vv = $array[$i];
}
}
$toc = microtime(true);
$time = $toc - $tic;
echo "Time for count(\$k)....: $time\n";
$tic = microtime(true);
for ($jj = 0; $jj < $iters; $jj++) {
foreach ($array as $i => $v) {
$vv = $array[$i];
}
}
$toc = microtime(true);
$time = $toc - $tic;
echo "Time foreach..........: $time\n";
Results:
Time for external $k..: 5.2356481552124
Time for count($k)....: 35.91916513443
Time foreach..........: 4.0548861026764
I think the following would be more efficient
for ($i = 0; $i < count($array); $i++)
{
echo $array[$i];
}
as no extra variable is defined to store the count of array requiring less memory space
<?php
foreach ($yourArayValue as $test=>$value)
{
echo $test;
}
?>
foreach() is batter
Related
Why this piece of code works when it is clearly wrong in the second for loop (for ($i==0; $i<$parts; $i++) {)?
Does php allows for multiple comparisons inside for loops?
function split_integer ($num,$parts) {
$value = 0;
$i = 0;
$result = [];
$modulus = $num%$parts;
if ($modulus == 0) {
for($i = 0; $i < $parts; $i++)
{
$value = $num/$parts;
$result[] = $value;
}
} else {
$valueMod = $parts - ($num % $parts);
$value = $num/$parts;
for ($i==0; $i<$parts; $i++) {
if ($i >= $valueMod) {
$result[] = floor($value+1);
} else {
$result[] = floor($value);
}
}
}
return $result;
}
Code for ($i==0; $i < $parts; $i++) runs because $i==0 has no impact on loop.
In normal for loop first statement just sets $i or any other counter's initial value. As you already set $i to 0 earlier, your loop runs from $i = 0 until second statement $i < $parts is not true.
Going further, you can even omit first statement:
$i = 0;
for (; $i < 3; $i++) {
echo $i;
}
And loop will still run 3 times from 0 to 2.
My target: create dynamic variables like
$counterMon00 = 0;
$counterMon01 = 0;
$counterThu23 = 0;
My code until now:
$array_days = ["Mon","Tue","Wed","Thu","Fri"];
for ($i = 0; $i < sizeof($array_days); $i++)
{
$weekDay = (String) $array_days[$i];
for($ii = 7; $ii < 10; $ii++)
{
"counter".${$weekDay}.${$ii} = 0;
}
}
Can You help my with this line
"counter".${$weekDay}.${$ii} = 0;
I tried different solution but nothing worked ...
You need to have the variable set as a single string before using it.
$var = "counter".$weekDay.$ii;
$$var = 0;
${"counter".$weekDay.$ii} = 0;
Try using variable variables:
$varName = "counter".${$weekDay}.${$ii};
$$varName = 0;//Note the $$
You also may want to look into building an array rather than the above as this would be easier (in my opinion at least). Something like an array mapping weekdays to counts i.e.
$arr["Mon"][3] = 0;
You want an array! That's exactly what they're for. Variable variables are a bad idea in 99% of all cases.
$counter = [];
$days = ["Mon","Tue","Wed","Thu","Fri"];
foreach ($days as $day) {
foreach (range(7, 9) as $i) {
$counter[$day][$i] = 0;
}
}
$array_days = array("Mon","Tue","Wed","Thu","Fri");
for ($i = 0; $i < count($array_days); $i++)
{
$weekDay = (String) $array_days[$i];
for($ii = 7; $ii < 10; $ii++)
{
$var="counter".$weekDay.$ii;
$$var;
}
}
Please try the following you make a mistake in the array declaration also
<?php
$array_days = array("Mon","Tue","Wed","Thu","Fri");
for ($i = 0; $i < sizeof($array_days); $i++)
{
$weekDay = (String) $array_days[$i];
for($ii = 7; $ii < 10; $ii++)
{
$var = "counter".$weekDay.(String)$ii;
$$var = 0;
}
}
?>
Try This
$array_days = ["Mon","Tue","Wed","Thu","Fri"];
for ($i = 0; $i < sizeof($array_days); $i++)
{
// $weekDay = $array_days[$i];
for($ii = 0; $ii < 5; $ii++)
{
//echo "counter".${$weekDay}.${$ii} = 0;
$a = "counter".$array_days[$i].$i.$ii;
$$a = 0;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get first element of an array
What is the fastest and easiest way to get the first item of an array in php?
I only need the first item of the array saved in a string and the array must not be modified.
I'd say that this is very optimized:
echo reset($arr);
I could not but try this out
$max = 2000;
$array = range(1, 2000);
echo "<pre>";
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = current($array);
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = reset($array);
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = $array[0];
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = &$array[0];
}
echo microtime(true) - $start ,PHP_EOL;
$start = microtime(true);
for($i = 0; $i < $max; $i ++) {
$item = array_shift($array);
}
echo microtime(true) - $start ,PHP_EOL;
Output
0.03761100769043
0.037437915802002
0.00060200691223145 <--- 2nd Position
0.00056600570678711 <--- 1st Position
0.068138122558594
So the fastest is
$item = &$array[0];
Use reset:
<?php
$array = Array(0 => "hello", "w" => "orld");
echo reset($array);
// Output: "hello"
?>
Note that the array's cursor is set to the beginning of the array when you use this.
Live demonstration
(Naturally, you can store the result into a string instead of echoing, but I use echo for demonstration purposes.)
Something like this?:
$firstitem = $array[0];
reset does this:
$item = reset($array);
This will work irrespective of what the keys are, but it will move the array pointer (I 've never had a reason to worry about this, but it should be mentioned).
The most efficient is getting the reference, so not string copy is involved:
$first = &$array[0];
Just make sure you don't modify $first, as it will be modified in the array too. If you have to modify it then look for the other answers alternatives.
i am facing a problem
can some one suggest me
for ($i = 1; $i <= 2; $i++) {
$r2 = 0;
for ($t = 1; $t <= 2; $t++) {
echo $r2;
$r2++
}
}
output is 0101;
can i get output 0123 ??? please
if
for ($i = 1; $i <= 3; $i++) {
$r2 = 0;
for ($t = 1; $t <= 3; $t++) {
echo $r2;
$r2++
}
}
output is 010101;
can output 012345678 ??? please
and if
for ($i = 1; $i <= 4; $i++) {
$r2 = 0;
for ($t = 1; $t <= 4; $t++) {
echo $r2;
$r2++
}
}
output is 01010101;
can output 0123456789101112131415 ??? please
i think you understand
thanks
In all of these cases you are initializing $r2=0; in the inner loop. It should be outside the loop.
$r2=0;
for($i=1;$i<=2;$i++){
for($t=1;$t<=2;$t++){
echo $r2;
$r2++
}
}
This would produce "1234".
why are you using two nested for loops ?
why not just use one:
for ($i=0; $i<=15; $i++) echo $i . " ";
Try this:
$r2 = 10;
for($t = 0; $t <= $r2; $t++){
echo $r2;
}
Oh wait.. I get it now, why you have the two nested loops, you want to essentially raise a number to the power of 2 in order to control the number of values output. In that case, what you want is simply this:
// this is the variable you need to change to affect the number of values outputed
$n = 2;
// Square $n
$m = $n * $n;
// Loop $m times
for ($i = 0; $i < $m; $i++) {
echo $i;
}
I have this code, but i want in second loop a decrease of $p value. The first internal loop must be repeated three times, the second, two times and the last, one time. I am trying $p-- but without success.
Any idea ? thanks
$p = 3;
for ($i = 0; $i < 3; $i++) {
for ($o = 0; $o < $p; $o++) {
echo "something";
$p--;
}
}
Move your $p-- to outside the inner for loop:
$p = 3;
for ($i = 0; $i < 3; $i++) {
for ($o = 0; $o < $p; $o++) {
echo "something";
}
$p--;
}
Or better, just depend on the value of $i:
for ($i = 0; $i < 3; $i++) {
for ($o = 0; $o < 3 - $i; $o++) {
echo "something";
}
}
Or if you don't actually use $i:
for ($i = 2; $i >= 0; $i--) {
for ($o = 0; $o < $i; $o++) {
echo "something";
}
}
It's quite simple.
for ($i = 2; $i >= 0; $i--)
{
}
Set the starting number at the upper limit number, and then go down until equal to 0, $i minus 1;
You need to decrement $p outside the first loop