By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,278 Members | 1,357 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,278 IT Pros & Developers. It's quick & easy.

Function returning an array ??

P: n/a
Not getting what I expect when I try to return an array from my
function. See sample below.

function test()
{
$myArray["one"] = 1;
$myArray["two"] = 2;
return $myArray;
}

$thisArray = test();
foreach($thisArray as $thisKey -> $thisVal)
{
echo($thisKey . " is " . $thisVal . "<br>");
}

// The output:
// Should Be: But Is:
// one is 1 Object is
// two is 2 Object is

What's up? How do I pass back an array from a function? I tried
passing it back as an &argument but that doesn't work either.
Jul 16 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On 18 Aug 2003 12:56:32 -0700, sa*******@yahoo.com (Texas Guy) wrote:
Not getting what I expect when I try to return an array from my
function. See sample below.

function test()
{
$myArray["one"] = 1;
$myArray["two"] = 2;
return $myArray;
}

$thisArray = test();
foreach($thisArray as $thisKey -> $thisVal)
{
echo($thisKey . " is " . $thisVal . "<br>");
}

// The output:
// Should Be: But Is:
// one is 1 Object is
// two is 2 Object is

What's up? How do I pass back an array from a function? I tried
passing it back as an &argument but that doesn't work either.
Output is in fact:
Notice: Undefined variable: thisVal in D:\public_html\test.php on line 10

Notice: Undefined variable: thisVal in D:\public_html\test.php on line 12
Object is

Notice: Undefined variable: thisVal in D:\public_html\test.php on line 10

Notice: Undefined variable: thisVal in D:\public_html\test.php on line 12
Object is

Having error_reporting set to E_ALL gives you more clues to work with.

Your problem is the loop, you're using the wrong operator:
foreach($thisArray as $thisKey -> $thisVal)


Should be:

foreach($thisArray as $thisKey => $thisVal)

-> is object access, => is for 'key => value' in foreach and array
construction.

Output with => is:

one is 1
two is 2

--
Andy Hassall (an**@andyh.co.uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
Jul 16 '05 #2

P: n/a
Texas Guy wrote:
foreach($thisArray as $thisKey -> $thisVal)

^^

Mind your syntax: You're trying to access an element in an Object here.
try "=>" instead and it works.

Jochen

--
/**
* @author Jochen Buennagel <zang at buennagel dot com>
* @see http://www.sourceforge.net/projects/zang
*/

Jul 16 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.