I'm a bit confused about array pointers in PHP. The below code worked fine:
$ages = [1, 3, 5];
while($age = current($ages)) {
echo $age . ", ";
next($ages);
}
But I've no idea why the below code didn't print any thing out:
$ages = [];
for($i = 0; $i < 10; $i++) {
$ages[] = $i;
}
while($age = current($ages)) {
echo $age . ", ";
next($ages);
}
I also tried to print with for loop, but in below code only the for loop printed, the while loop still didn't print.
$ages = [];
for($i = 0; $i < 10; $i++) {
$ages[] = $i;
}
for($i = 0; $i < 10; $i++) {
echo $ages[$i] . ", ";
}
while($age = current($ages)) {
echo $age . ", ";
next($ages);
}
I'm really not sure why it behaved like this, anyone could help me out?
You will need to check if the result of current()
is different from the boolean false
(means the cursor did not find the element), not just assign its value. As when the value is 0
, you get while(0)
, which breaks the loop.
$ages = [];
for($i = 0; $i < 10; $i++) {
$ages[] = $i;
}
while($age = current($ages) !== false) {
echo $age . ", ";
next($ages);
}
However, this will fail should any of the elements in the array have the value of boolean false
. Its therefor not recommended to iterate over the array like this at all, you should instead be using the proper tools, by using a foreach
loop. This doesn't actually move the cursor, but you can "make" it move the cursor by calling next()
for each iteration.
$ages = [];
for($i = 0; $i < 10; $i++) {
$ages[] = $i;
}
foreach ($ages as $age) {
echo current($ages).", ";
next($ages);
}
If you're just looking to print the values, the best way would be either printing directly from the foreach
loop, or by using implode()
.
foreach ($ages as $age) {
echo $age.", ";
}
or
echo impolode(",", $ages);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다