<?php
//I have an array like this
$ar = array('0', '1', '2', '3', '4', '5');
for($i = 0; $i < count($ar); $i++)
{
echo $ar[$i+1]; //way1
echo $ar[$i] +=1 //way2
}
?>
So is it different between way1 and way 2 because i saw the same result ???
Please clarify what exactly you're looking for here.
These two are totally different approaches and give you different results when your array values are something else.
echo $ar[$i+1]; // Means you're printing the values corresponding to array keys 1, 2, 3.....
echo $ar[$i] +=1 // Means you're getting the values of keys 0, 1, 2... and adding 1 to each of the values.
If you have an array $ar = array(3, 6, 2, 10), these two will work this way:
echo $ar[$i+1]; // 6, 2, 10 ....
echo $ar[$i] +=1 // 4, 7, 3, 11....
Hope this helps.
Peace! xD
of course not.
Notice, your code need ";"
after way2
way1
echo the (i+1)
-th item in the array.
way2
echo the i-th
item'value + 1
so, if you change the array, the result may be different.
e.g.
$ar = array('1','3','4');
then,
way 1 will output:
3,4
and catch a OutOfRange Exception
(because it asked the $ar[3]
,which is not exist.)
way2 will output:
2,4,5
Here the difference is to use Assignment operator and Increment Operator.
In a first way :
$ar[$i+1] will print array element at the index of $i + 1
, It means 1 in first iteration of loop.
echo $ar[$i + 1];
$ar[0 + 1];
$ar[1];
So It will look for the value of index 1 and that is 1.
Notice: While looping, when loop reach to last iteration then your statement will look like this:
echo $ar[$i + 1];
$ar[5 + 1];
$ar[6];
It will show a notice for undefined index because index 6 is not assigned any value in your array.
In a second way :
Here increment operator is used. So the statement will become like this:
echo $ar[$i] = $ar[$i] + 1;
So first, 1 will be added to $ar[$] and then assign to it. And Then after it will echo that updated value. In first iteration of loop it will be:
echo $ar[$i] = $ar[$i] + 1;
$ar[$i] = 0 + 1;
finally Ans will be 1;