Jump to content

Function to return several useable vars?


TEENFRONT

Recommended Posts

Hey all

 

Is it possible to have a function return more than one var?

 

For example

 

function test() {
//do something
$title = "batman";
return $title;
}


echo test();   // echos batman

 

But what if I want to use several things from the function like $title $cast $rating etc?

 

In separate areas around my page. Basically, I'm making a movie review page, I want a function that builds the review bits up. Then I can echo the various bits around the page.

 

So basically can I do this?

 

<?

function buildReview() {
// get review data from mysql 

Return $title $cast $review $poster
}

Echo "<title>$title</title>
<img src=\"$poster\">
";

// and so on...
?>

 

so instead of just echo the function, can I echo the returned vars in a function?

 

Cheers!!

 

Link to comment
https://forums.phpfreaks.com/topic/207164-function-to-return-several-useable-vars/
Share on other sites

You can return an array that holds the values and use list to get the individual variables:

<?php
function buildReview() {
// get review data from mysql 

Return array($title, $cast, $review, $poster);
}

list($title, $case, $review, $poster) = buildReview();
?>

 

Ken

beaten to it :)

 

When you're returning multiple values from functions you'll want to use an array.

 

eg

function buildReview() {
// get review data from mysql 

Return array($title, $cast, $review, $poster);
}

list($title, $cast, $review, $poster) = buildReview();

Echo "<title>$title</title>
<img src=\"$poster\">
";

// and so on...
?>

I thought I hit post earlier but evidently not.

 

You can return a more sensible array to use as an array or as individual vars:

 

function buildReview() {
   // get review data from mysql 
   return compact('title', 'cast', 'review', 'poster');
}

$info = buildReview();
echo $info['title'];

//or

extract(buildReview());
echo $title;

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.