Jump to content

access two variables from function


giraffemedia

Recommended Posts

Hello,

 

is it possible to access two variables from a single function if I'm using explode to split a string? Something like…

 

function advert_type($advert_string) {
$advert_type = explode(' - ', $advert_string);
$advert_type = $advert_type[0]; // Variable 1
$advert_type_choice = $advert_type[1]; // Variable 2
return $advert_type;
return $advert_type_choice;
}

echo advert_type('Test - Value');

 

Thanks, James

Link to comment
https://forums.phpfreaks.com/topic/226555-access-two-variables-from-function/
Share on other sites

You would return an array with the pieces you want as elements in the array.

 

I'm not sure how I access the array though I've tried the following with no success…

 

function advert_type($advert_string) {
$advert_type = explode(' - ', $advert_string);
$advert_type = $advert_type[0];
$advert_type_choice = $advert_type[1];
return array($advert_type ,$advert_type_choice);
}
$test = 'Test - Value';

list ($advert_choice) = advert_type($test);

the code was immediately overwriting $advert_type. you need to use different variable names:

 

// WRONG
$advert_type = explode(' - ', $advert_string);
$advert_type = $advert_type[0]; // Variable 1 OVERWRITES $advert_type.

 

 

function advert_type($advert_string) {
$advert_type_parts = explode(' - ', $advert_string);
$advert_type = $advert_type_parts[0];
$advert_type_choice = $advert_type_parts[1];
return array($advert_type ,$advert_type_choice);
}
$test = 'Test - Value';

list ($advert_choice,$advert_type_choice) = advert_type($test);
echo "advert_choice: $advert_choice <br />";
echo "advert_type_choice: $advert_type_choice <br />";

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.