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
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);

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.