The reason your extract is not working is because you need to return an associative array. You can do this manually, or you can use compact properly by passing variable names, not variable values:
function my_function() {
$var = 'Happy';
$var2 = 'New';
$var3 = 'Year';
return array(
'var' => $var,
'var2' => $var2,
'var3' => $var3
// ... etc ...
);
// Alternate method, with compact
return compact('var', 'var2', 'var3');
}
$values = my_function();
extract($values);
echo $var; // outputs 'Happy'
echo $var2; // outputs 'New'
echo $var3; // outputs 'Year'
Edit
Extract is not best-practice. When reading the code, it's a mystery where the variables suddenly appear from, and makes it more difficult to maintain.
Better would be to check / get the values explicitly from the array:
$values = my_function();
$var = $values['var'];
$var2 = $values['var2'];
$var3 = $values['var3'];
echo $var; // outputs 'Happy'
echo $var1; // outputs 'New'
echo $var3; // outputs 'Year'
Depending on the structure of your code, you have to decide if you can rely on that function to always return those values, or if you need to check them. If you need to check multiple keys / values, then I typically like to write a utility function for that sort of thing:
function get_val( $key, $array, $default = FALSE) {
$array = (array)$array;
return ( isset( $array[ $key ] ) ) ? $array[ $key ] : $default;
}
Then, you'd use it like so:
$values = my_function();
$var = get_val( 'var', $values );
$var2 = get_val( 'var2', $values );
$var3 = get_val( 'var3', $values );
echo $var; // outputs 'Happy'
echo $var1; // outputs 'New'
echo $var3; // outputs 'Year'
Lastly, your function that returns the row from the DB should probably be responsible for doing the validation / returning something meaningful. For example, if no rows, then return FALSE, then you can check like so:
function my_function( $id ) {
// your code to get the row based on the id
// then, check that a row was returned...
if ( ! count( $row ) ) {
return FALSE;
} else {
// return the row
}
}
$values = my_function();
if ( $values !== FALSE ) {
// do stuff, because we know we have a valid row
}