0

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

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by ppetree
0

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);
?>
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.