1

I was trying to echo all the values of the $sel_arrays using the foreach loop within a function called country(). I was using the loop within the country() function and return the value $sel. But it does output only the single value Bangladesh. I want to get the all values of the $sel_arrays.Though I know that foreach loops iterates all the arrays values, But these codes does not give my expected result. Below my codes...

    <?php 
    function country() {
        $sel_arrays = array('Banglasesh','Pakistan','USA','India','Italy');

        foreach( $sel_arrays as $sel ) {
            return $sel;
        }
    }
    echo country(); // output only Bangladesh. That i ain't wanting.
    ?>

I did not get it how it is happening. Please help to get all the values of the array.

2
  • Instead of return $sel; do echo $sel; Commented Feb 6, 2016 at 13:01
  • Why you are using foreach loop, if you need to get $sel_arrays.. Just return $sel_arrays variable and remove foreach loop.. Commented Feb 6, 2016 at 13:56

2 Answers 2

1

Your function returns, and then exits the function, in the first iteration. This is how return works. To work around it, you could add all the values to a string, and echo that string instead.

function country() {
    $sel_arrays = array('Banglasesh','Pakistan','USA','India','Italy');

    $result = "";
    foreach( $sel_arrays as $sel ) {
        $result .= $sel." ";
    }
    return $result;
}
echo country(); // outputs everything, separated by a space

Reference

Sign up to request clarification or add additional context in comments.

Comments

0
function country() {
    $sel_arrays = array('Banglasesh','Pakistan','USA','India','Italy');

    foreach( $sel_arrays as $sel ) {
        echo $sel;
    }
}

country(); // output only Bangladesh. That i ain't wanting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.