Jump to content

can an array created in a function be available outside?


jasonc

Recommended Posts

I have the following that i am stil working on but wish to know if this will work when finished.

 

// split up the string in to an array.
  function split_to_array($string) {
  // can I do this?  will the array be usable from outside this function?
  $newarray = preg_split("/\|\|/",$string); // split each section up where the || divider is.
    return $newarray;
  }

You have to assign the function call to a variable so that the returned $newarray gets passed back:

 

$array = split_to_array($string);

 

Then $array will have the value of $newarray value.

 

Alternatively, you can do like

 

global $newarray;

 

at the beginning, inside your function.  This will make $newarray globally scoped.  Then you won't have to return anything.  However, I do not recommend doing this.  Go for the first suggestion: assign the returned value to a variable.

 

p.s.- as nightslyr mentioned, explode() is better.  It is optimized for splitting strings by another static string.  You should only use preg_split if you are trying to split by a non-static pattern.

 

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.