Your code ends up with Fatal error, since at the second iteration it tries to redeclare function myfunction
. That's why it is printing only first value of array.
In order to avoid that fatal error you can check if that function has been already defined using function_exists()
function like this:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
if(!function_exists('myfunction'))
{
function myfunction($value) {
//Do something
}
}
echo $val;
}
PHP is a scripting language and it is syntactically correct to declare a function inside for loop or inside if statement, but it is a bad practice and can cause a lot of errors afterwards.
The best way is to declare a function outside loop, and, if needed, call it from within a loop like this:
<?php
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($value); //may you was intended to pass $val here?
echo $val;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…