using variables outside of a function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Alski
Forum Newbie
Posts: 2
Joined: Tue Aug 10, 2010 12:19 am

using variables outside of a function

Post by Alski »

Hi - I have been playing with the following code (taken from http://php.net/manual/en/function.explode.php)

Code: Select all

<?php
print_r(explodeX(Array(".","!"," ","?",";"),"This.sentence?contains wrong;characters"));
// Returns:
// Array("This","sentence","contains","wrong","characters")

function explodeX($delimiters,$string)
{
    $return_array = Array($string); // The array to return
    $d_count = 0;
    while (isset($delimiters[$d_count])) // Loop to loop through all delimiters
    {
        $new_return_array = Array();
        foreach($return_array as $el_to_split) // Explode all returned elements by the next delimiter
        {
            $put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);
            foreach($put_in_new_return_array as $substr) // Put all the exploded elements in array to return
            {
                $new_return_array[] = $substr;
            }
        }
        $return_array = $new_return_array; // Replace the previous return array by the next version
        $d_count++;
    }
    return $return_array; // Return the exploded elements
}
?>

How do I put the words "This" and "sentence" in separate variables that I can use OUTSIDE of the function?


If I write the following:

Code: Select all

    }
    //return $return_array; // Return the exploded elements

  $firstword = $return_array[0];
  $secondword = $return_array[1];

  echo $firstword;
  echo $secondword;
}
it outputs "This" and "sentence" but if I want to pass the $firstword outside of the function, it fails.

Any idea how I can use the $firstword variable?

Cheers,
Alski
internet-solution
Forum Contributor
Posts: 220
Joined: Thu May 27, 2010 6:27 am
Location: UK

Re: using variables outside of a function

Post by internet-solution »

The clue is in the code

Code: Select all

//return $return_array; // Return the exploded elements
Alski
Forum Newbie
Posts: 2
Joined: Tue Aug 10, 2010 12:19 am

Re: using variables outside of a function

Post by Alski »

help me out here - I'm learning :)
Post Reply