Jump to content

A Problem of Scope?


iwato

Recommended Posts

Please consider the following two blocks of independently run code and explain why the first block works and the second does not.BLOCK ONE

<?php	$selectedCountry = $_GET['countrylist'];	$selectedCities = $_GET['citylist'];	$numberOfSelectedCities = count($selectedCities);	echo $selectedCities[1];?>

BLOCK TWO

<?php	$selectedCountry = $_GET['countrylist'];	$selectedCities = $_GET['citylist'];	$numberOfSelectedCities = count($selectedCities);	function writeCities() {		   echo $selectedCities[1];	}	writeCities();?>

For the second block of code PHP responds with an error telling me that $selectedCities is undefined in the function writeCities().Roddy

Link to comment
Share on other sites

Please consider the following two blocks of independently run code and explain why the first block works and the second does not.BLOCK ONE
<?php	$selectedCountry = $_GET['countrylist'];	$selectedCities = $_GET['citylist'];	$numberOfSelectedCities = count($selectedCities);	echo $selectedCities[1];?>

BLOCK TWO

<?php	$selectedCountry = $_GET['countrylist'];	$selectedCities = $_GET['citylist'];	$numberOfSelectedCities = count($selectedCities);	function writeCities() {		   echo $selectedCities[1];	}	writeCities();?>

For the second block of code PHP responds with an error telling me that $selectedCities is undefined in the function writeCities().Roddy

I would guess what you need to define the varible inside the function unless it's global so this would work couse I define it in the function:
<?php	$selectedCountry = $_GET['countrylist'];	$selectedCities = $_GET['citylist'];	$numberOfSelectedCities = count($selectedCities);	function writeCities($city) {		   echo $city;	}	writeCities($selectedCities[1]);?>

Link to comment
Share on other sites

I would guess what you need to define the varible inside the function unless it's global so this would work couse I define it in the function.
Yes, your suggested modification worked.I am slowly learning that PHP is not ActionScript.Great job! Thanks.Roddy
Link to comment
Share on other sites

You could have also just used the global keyword:

<?php	$selectedCountry = $_GET['countrylist'];	$selectedCities = $_GET['citylist'];	$numberOfSelectedCities = count($selectedCities);	function writeCities() {		   global $selectedCities; //This allows you to reference global variables		   echo $selectedCities[1];	}	writeCities();?>

Link to comment
Share on other sites

You could also pass it to the function:

<?php	$selectedCountry = $_GET['countrylist'];	$selectedCities = $_GET['citylist'];	$numberOfSelectedCities = count($selectedCities);	function writeCities($list) {		   echo $list[1];	}	writeCities($selectedCities);?>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...