Jump to content

return value with function


Orasion
 Share

Recommended Posts

Hi all,

 

can you give me suggestion how to return value from function like this

 

function returnArray(){
for($i=1; $i<=3; $i++){
	return $i; //how to return this as array??
}
}

 

when I code "echo" inside the function then call the function it give me output => 123

but when I code "return" inside the function, it will give output => 1

Can you suggest me how to output it as array?

 

Link to comment
Share on other sites

In your example $i isn't an array.

 

function returnArray() {
        $foo = array();
for($i=1; $i<=3; $i++){
	return $foo[] = i;
}
        return $foo;
}

 

Will return an array containing the number 1 - 3. Of course you could more easily achieve the same result by using:

 

$foo = range(1,3);

Link to comment
Share on other sites

There is a typo in my reply, should be:

 

function returnArray(){
$foo = array();
for($i=1; $i<=3; $i++){									
	$foo[] = $i;
}
return $foo;
}

 

Note you don't want to call return part why through the loop.

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.