Welcome to OStack Knowledge Sharing 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...