Jump to content

Odd array behaviour


Nodral

Recommended Posts

Hi All

 

I have a script which creates a csv file with random entries.

 

It should pick a country from an array (this is defined in countries.php), pick 4 letters, create a random price and a random 8 digit number then write each one to a line in the file.

 

This works apart from one exception.  When the country is chosing $country[0] it appends it to the previous line of the file.

 

any ideas?

 

$handle = fopen($file, 'a') or die("can't open file");

for ($i=1; $i<=500; $i++){
   
   //get country
   include ('countries.php');
   $countries=$country[array_rand($country)];

   // create ACCRISS code
   $first=array ("C", "E", "F", "G", "I", "L", "M", "O", "P", "S", "T", "U", "V");
   $second = array ("C", "D", "E", "F", "G", "M", "P", "V", "W", "X");
   $third = array ("A", "M");
   $fourth = array("N", "R");
   $accriss= $first[array_rand($first)].$second[array_rand($second)].$third[array_rand($third)].$fourth[array_rand($fourth)];

   //create price
   $pounds= rand(1,99);
   $pence=rand(0,99);
   $price="$pounds.$pence";	   
   $price="£".number_format($price,2);
   
   //create account numbers
   $number = rand(10000000,99999999);


   // add new row to output
   fwrite($handle,"$countries,$accriss,$price,$number");

   $place[]=$countries;
   $car[]=$accriss;
   $cost[]=$price;
   $account[]=$number;
   }
   
//echo $output;
fclose($handle);

 

<?php
//countries.php
$country= array("Albania","
Antigua","
Argentina","
Aruba","
Australia","
Austria","
Bahamas","
Bahrain","
Belgium","
Benin","
Bosnia","
Botswana","
Bulgaria","
Burkina Faso","
Cameroon","
Chile","
Colombia","
Croatia","

This file goes on for about 150 countries but only Albania gets added to the current line instead of starting a new line.

Link to comment
https://forums.phpfreaks.com/topic/248891-odd-array-behaviour/
Share on other sites

sorry, I meant .csv (.txt .csv, same thing to me, they are flat text files...) if you open your .cvs in notepad, does it also contain the weird  thing? or only in excel?

Try opening it in an editor that will allow you to change the encoding, or create a new one with the same encoding you're using in php.

Link to comment
https://forums.phpfreaks.com/topic/248891-odd-array-behaviour/#findComment-1278205
Share on other sites

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.