giraffemedia Posted February 3, 2011 Share Posted February 3, 2011 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 More sharing options...
PFMaBiSmAd Posted February 3, 2011 Share Posted February 3, 2011 You would return an array with the pieces you want as elements in the array. Link to comment https://forums.phpfreaks.com/topic/226555-access-two-variables-from-function/#findComment-1169340 Share on other sites More sharing options...
giraffemedia Posted February 3, 2011 Author Share Posted February 3, 2011 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); Link to comment https://forums.phpfreaks.com/topic/226555-access-two-variables-from-function/#findComment-1169350 Share on other sites More sharing options...
BlueSkyIS Posted February 3, 2011 Share Posted February 3, 2011 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 />"; Link to comment https://forums.phpfreaks.com/topic/226555-access-two-variables-from-function/#findComment-1169398 Share on other sites More sharing options...
giraffemedia Posted February 3, 2011 Author Share Posted February 3, 2011 Works like a dream, and I understand your point about overwriting the variable. Thanks very much. James Link to comment https://forums.phpfreaks.com/topic/226555-access-two-variables-from-function/#findComment-1169420 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.