Jump to content

accessing an array that was created inside a function


poe

Recommended Posts

lets say i have:
function makeName($fullNameString) {
  list($fn, $mn, $ln) = split(":", $fullNameString);
  $nameArray[] = array($fn, $mn, $ln, );
}// end function

i want my array to eventually looks like this:
  $nameArray[] = array('chris', 'w', 'smith', );
  $nameArray[] = array('pam', 't', 'lee', );
  $nameArray[] = array('mary', 'g', 'smith', );
  $nameArray[] = array('kim', 'a', 'jones', );

how do i access the "nameArray" later on such as:
foreach($nameArray as $k => $v){
echo "hello ".$v[0];
}

since the 'namearray' was created inside a function i cant get it to show results.
Return the array.

Add this line just after ech "hello ".v[0]:

return $nameArray;
[code]
$name = makeName("chris:w:smith");
echo "<br />First Name:  " . $name[0];
echo "<br />Middle Initial:  " . $name[1];
echo "<br />Last Name:  " . $name[2];
[/code]
There's three ways I can think of: 1) pass variable by reference, 2) use global keyword, and 3) have the function return the value.

Here's an example of having the function return the value desired. In this case an array:

[code=php:0]
function makeName($fullNameString) {
  return split(":", $fullNameString);
}// end function

$nameArray[] = makeName('chris:w:smith');
$nameArray[] = makeName('pam:t:lee');
$nameArray[] = makeName('mary:g:smith');
$nameArray[] = makeName('kim:a:jones');

foreach ($nameArray as $aryUser) {
  echo "Hello ", $aryUser[0];  // Display first name
}
[/code]

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.