returning variable from a function

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
SFADuncan
Forum Newbie
Posts: 23
Joined: Mon Aug 11, 2003 5:06 pm
Location: uk

returning variable from a function

Post by SFADuncan »

This works fine. It sends $title off to another function which displays $title the way I need.

Code: Select all

function extract_title1($published_page)
{
  if (is_array($published_page))
  {
  	foreach ($published_page as $row)
  	{
	$title = $row['title1'];
  	}
  }
  display_hm_title($title);
}
But what I really want to do is return $title somewhere else before sending it to another function. ie I want to return $title, but I can't. I've tried several derivations of the following but it's failing to return $title every time:

Code: Select all

function extract_title1($published_page)
{
  if (is_array($published_page))
  {
  	foreach ($published_page as $row)
  	{
	$title = $row['title1'];
  	}
  }
  return $title;
}
Any ideas?

Simon

Jcart | Please review :arrow: Posting Code in the Forums
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

In your function(s) you should look at making title an array or atleast one long string and passing the array through the return. The way you have it setup is you repeatedly overwrite $title and return the last instance of it.
SFADuncan
Forum Newbie
Posts: 23
Joined: Mon Aug 11, 2003 5:06 pm
Location: uk

Post by SFADuncan »

I'm convinced you are right, but I'm not sure how to do it... I've tried the following but it doesn't work.

Code: Select all

function extract_title1($published_page)
{
  if (is_array($published_page))
  {
   $title = array();
   foreach ($published_page as $row)
   {
   $title[] = $row['title1'];
   }
  }
  return $title;
}

I'm calling the function like this:

Code: Select all

extract_title1($published_page);
thegreatone2176
Forum Contributor
Posts: 102
Joined: Sun Jul 11, 2004 1:27 pm

Post by thegreatone2176 »

i dont really see the point of what your code is doing but i dont think you can do $row['title1'] like with mysql i think you should try $row[0] or w/e element it is you are trying to extract.
Post Reply