Returning arrays from a function in PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Returning arrays from a function in PHP

Post by mjseaden »

Dear All

If I have a function return_strings($itemID), can I make it return an array of values? For example, could I do this -

$string1 = return_strings(5)[1];
$string2 = return_strings(5)[2];
$string3 = return_strings(5)[3];

It doesn't seem intuitively that this would be the case - in which case, is there any other way of doing this?

Many thanks

Mark
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

/bump
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

It doesn't work by the way - it produces a parse error when I attempt to call the function with the above syntax.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

You can have functions return an array although I would try to create the array with a meaningful index:

Code: Select all

function getArray() {
    $retval=array("name"=>"CoderGoblin","desc","PHP Coder");
    return $retval;
}

// Get result of array
$my_array=getArray();

// process the individual columns
$my_name=$my_arrayї'name'];
$my_desc=$my_arrayї'desc'];
using

Code: Select all

$string1 = return_strings(5)ї1];
$string2 = return_strings(5)ї2];
$string3 = return_strings(5)ї3];
would call the function 3 times.
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

Many thanks CoderGoblin - you're a star!
Post Reply