Function returning an array ??

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Texas Guy

    Function returning an array ??

    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($thisAr ray 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.
  • Andy Hassall

    #2
    Re: Function returning an array ??

    On 18 Aug 2003 12:56:32 -0700, satxguy58@yahoo .com (Texas Guy) wrote:
    [color=blue]
    >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($thisA rray 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.[/color]

    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:
    [color=blue]
    >foreach($thisA rray as $thisKey -> $thisVal)[/color]

    Should be:

    foreach($thisAr ray 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 (andy@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk)
    Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)

    Comment

    • Jochen Buennagel

      #3
      Re: Function returning an array ??

      Texas Guy wrote:
      [color=blue]
      > foreach($thisAr ray as $thisKey -> $thisVal)[/color]
      ^^

      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
      */

      Comment

      Working...