Can anyone tell me why this code is not working? It outouts 8 colons, one for each element but no data which means the [$i] is NOT referencing the array element

$geo_addr = array("number"=>1600, "zip"=>34208, "suffix"=>'', "prefix"=>'', "type"=>'parkway', "street"=>'amphitheatre', "state"=>CA, "city"=>'mountain view');
$count = count($geo_addr);
for($i=0; $i<$count; $i++)
{
  echo $geo_addr[$i]; 
  $geo_addr[$i] = str_replace(" ", "+", $geo_addr[$i]);
  echo ": " .$geo_addr[$i] ."<br>"; 
}
extract($geo_addr);

The output should show that $geo_addr gets changed from "mountain view" to "mountain+view".

Thanks!

Pete

Recommended Answers

All 2 Replies

You are trying to refer to numeric keys in an associative array. If you run this script with error_reporting(E_ALL) turned on, you'll see notice messages like this: Notice: Undefined offset: 0 in C:\www\webroot\DaniWeb\arraytest.php on line 10 For an associative array, use foreach instead.

<?php
$geo_addr = array("number"=>1600, "zip"=>34208, "suffix"=>'', "prefix"=>'', "type"=>'parkway', "street"=>'amphitheatre', "state"=>'CA', "city"=>'mountain view');

foreach($geo_addr as $key => $value)
{
  $geo_addr[$key] = urlencode($value);

  echo $geo_addr[$key]."<br />\n";
}

// another way:
function urlencodeWrapper(&$value, $key, $user)
{
  $value = urlencode($value);
}

array_walk($geo_addr, urlencodeWrapper);

extract($geo_addr);
?>

thanks for that... I thought associative arrays could be referenced either way...

I ended up doing an array_walk() which was just as easy or easier... thanks for that too!

Pete

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.