Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a problem trying to run a code inside the loop, my loop consist of a function.

Here is my coding:

$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];



function myfunction($value) {   
    //Do something
}

echo $val;
}

The problem is the code outputs only the 1st value in my array. I am very confused, am I not suppose to declare a function inside the loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
935 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...