Jump to content

[SOLVED] Creating a function to return more than 1 variable


chris_2001

Recommended Posts

I want to create a function that will return more than 1 variable. What I want it to do is connect to a sql database by parameters you set with the function and return more than two pieces of data (in some cases 10).

 

function test($table, $search, $value)
{
$query = "SELECT test1, test2, test3 FROM $table WHERE $search = '$value'";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$test1 = $row['test1'];
$test2 = $row['test2'];
$test3 = $row['test3'];
}

 

Above is an example of what I want it to do. How do I make it return $test1 - $test3? Thanks.

Yeah I was attempting to avoid using an array :/ if i were to return $test1 for example, once out of the function what would it read $test1 as? Could i do for example

 

echo "$test1";

 

or would it be given a different name?

They only way is to return an array. Example

function test($table, $search, $value)
{
    $query = "SELECT test1, test2, test3 FROM $table WHERE $search = '$value'";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result, MYSQL_ASSOC);

    return $row;
}

$row = test($table, $search, $value);

echo $row['test1'];
echo $row['test2'];
echo $row['test3'];

// or alternatively, but not recommended
extract($row);

echo $test1;
echo $test2;
echo $test3;

if i were to return $test1 for example, once out of the function what would it read $test1 as? Could i do for example

 

echo "$test1";

 

or would it be given a different name?

 

if you return something from a function it will be assigned to the var that called the function, so...

 

function something() {
   $x = rand(1,5);
   return $x;
}

// the random number would be assigned to $y... it would be "called" $y
$y = something();

I'm surprised no one mentioned pass by reference.

 

<?php

$a = 'hello';
$b = 'foo';

passByRef( $a, $b );

echo "$a<br />$b";

# A an argument is 'pass by reference' if an & is put before the variable
function passByRef ( & $str1, & $str2 ) {
$str1 .= ' world';
$str2 .= 'bar';
}

?>

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.