0

I'm trying to process an array from data posted from a textbox.
I've written the following code to trim each new line and I have nearly everything working perfectly except one thing. I believe I need to iterate my numeric array through this GeoIP function:
$record = geoip_record_by_addr($gi,$value);, but it only processes the last IP in the array, and not the entire thing.

My var_dump: string(12) "65.87.12.213" string(12) "13.15.200.36"

$gi = geoip_open("/tmp/GeoIPCity.dat",GEOIP_STANDARD);

$iips = explode("\n", $_POST["ip"]);
$iiips=array_map('trim',$iips);
foreach($iiips as $key => $value) {
    $record = geoip_record_by_addr($gi,$value);
}
print $record->city . "\n";
print $record->region . " " . "\n";
print $record->country_name . "\n";

$record1 = $record->city . " " . $record->region . " " . $record->country_name;

var_dump($record1);

Is there anybody that can please help?

2 Answers 2

2

Inside the foreach loop you overwrite the $record variable all the time, so at the end you have the last one.

Store all records into another array instead and you should be fine.

So this is just a more or less simple mistake you made.

$records = array();
foreach ($iiips as $key=>$value) {
    $records[] = geoip_record_by_addr($gi, $value);
}

foreach ($records as $record) {

    echo $record->city, "\n",
         $record->region, "\n",
         $record->country_name, "\n";

    $record_string = $record->city . " " . $record->region . " " . $record->country_name;

    var_dump($record_string);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of $record = geoip_record_by_addr($gi,$value);, do this:

$record = array();
foreach($iiips as $value) { // key isnt needed.
    array_push($record, geoip_record_by_addr($gi,$value));
}

Then you're free to use the contents of $record as you expected. Re-assigning a variable in any loop will change the value of that specific variable each time. PHP doesn't know that you're using an array unless you tell it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.