Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - Running a loop that has a function inside it

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...