Re-arranging lines in a file - php

I'm trying to read data from a text file and assign it to arrays. How could I read exactly 3 lines at a time, and then assign the first line to array $a, second line to array $b, third line to array $c? and then read exactly 3 more lines, etc.

$lines = file('some_file.txt');
$numLines = count($lines);
for ($i = 0; $i < $numLines; $i += 3) {
$a[] = $lines[$i];
$b[] = $lines[$i + 1];
$c[] = $lines[$i + 2];
}
Note that you'll want to do some out-of-bounds index error checking, as well. I leave that as an exercise for the OP.

The example for fgets should give you some ideas:
http://php.net/manual/en/function.fgets.php#refsect1-function.fgets-examples

you can use something like this for example:
$lines = file('filename');
$chunks_array = array_chunk($lines, 3)); - this create array of arrays with 3 lines each
foreach ($chunks_array as $chunks)
{
$a[] = $chunks[0];
$b[] = $chunks[1];
$c[] = $chunks[2];
}

Once I had a similar problem. I solve like this (in pseudocode).
counter = 1;
while reading
switch counter
case 1: store in the first array then break;
case 2: store in the second array then break;
case 3: store in the third array, counter = 0, then break;
counter++;
end-while

You could use fseek, or file_get_contents with maxlen parameter. But to read exactly 3 lines, I don't actually know, unless you know how long are these lines.
function file reads all lines into an array.
Edit two:
Could read the file byte by byte (although a bad idea from my point of view) and stop after you encounter each \n or PHP_EOL and use a counter or whatever to manage how it is used.
Edit one:
I just got this idea: you could create a custom stream wrapper, and handle your reading the lines 3 by 3 with it. It is a great tool for files, check http://www.php.net/manual/en/class.streamwrapper.php , and control it with through context or variables, or what ever.
I guess you still will have to find an algorithm for this. I didn't tried this yet, but let us know if you handle it.

Related

How to loop though an array and create an array, in the loop, containing values from the original array?

Hey everyone I have a question about arrays and loops in PHP.
For a game I'm making, I need to write a function that generates a stack of crystal_id's based on a given size and ratio.
The ratio is the ratio between black crystals and different colored crystal (so a ratio of 0,25 (1:4) and a stack of 50 would yield a stack with 40 black crystals and 10 colored crystals).
I have all the math to calculate the amount of crystals per color and stuff figured out, but I can't figure out how to create an array with the right amount of colored crystals where each color is represented equally.
For reference, the array the code gets to choose from is a variable called $crystals_array, which is an array filled with integers where each integer represents a different colored crystal (e.g. [2,3,4,5,6]).
In the above case we have 5 different colored crystals and we needed a total of 10 colored crystals where each crystal is represented equally. So I need to create an array that looks a little something like this:
[2,2,3,3,4,4,5,5,6,6].
The code I have so far is this:
for($i = 0; $i <= count($amount_crystals_color) - 1; $i++)
{
$array = array_fill(0, $amount_crystals_per_color_stack, $crystals_array[$i]);
$i++;
}
Using the above example $amount_crystals_per_color_stack is equal to 2 and amount_crystals_color is equal to 5.
When executing this code it outputs an array: [2,2] which is how many 2's we need, but I can't figure out how to add the remaining crystals to this array.
Can anyone help me out?
Your code has several problems and i will address each of them individually.
Using the for loop to iterate over an array
You are using a for loop in your code, that has the following loop head:
for($i = 0; $i <= count($crystals_array) - 1; $i++)
The loop had consists of three parts, each separated by a semicolon (;).
The first part $i = 0 is the initialization part. Here you initialize a variable, that is later used as an iterator, which shall change in each loop iteration. You could name this the start point as well.
The second part $i <= count($crystals_array) - 1 is the condition part. A condition is formed, that shall express for how long the loop shall iterate. As long as the expression evaluates as true, the loop will run again. Therefore this condition is evaluated at the start of each iteration. As soon as the condition evaluates as false the loop will end. Therefore this part can be named endpoint as well.
The third part $i++ is the step size. This is executed at the end of each iteration and determines how the iterator (the variable you defined in the first part) shall change. $i++ is in this context equal to $i = $i + 1 and represents a step size of 1. Therefore the variable $i gets increased by 1 for each run of the loop.
This said, you can improve and fix your code regarding the for loop with two changes:
Save functions, that are executed in your condition part into an variable, if they return a constant result for each iteration. You use the count() function, which will then count your array again for each iteration of the for loop. By saving it in a variable $count = count($crystals_array); before the for loop and changing the condition to $i < $count, the function is only called once and your code gets faster.
Do not change the iterator variable $i outside of your loop header. This is really bad code style. You added the line $i++; to the end of your loop, but that is already done in the step size part of the for header. Because that is executed at the and of each iteration as well you increased the step size to two, meaning that you only run the for loop with $i = 0, $i = 2 and $i = 4 instead of for each element.
For your code the usage of the $i iterator is only to address the elements of the initial array. Even though you should understand the for loop for the future, you should use a foreach loop for this case instead. The following code would be equivalent to your for loop.
//This code still contains another major bug and is jsut a partial improvvement
foreach($crystals_array as $crystal) {
$array = array_fill(0, $amount_crystals_per_color_stack, $crystal);
}
As you can see, you neither need to worry about counting the initial array, nor in which index the current value is. Instead the variable $crystal will automatically contain the next element for each iteration.
Appending elements to an array
You used the following line to save the newly generated elements in your array:
$array = array_fill(0, $amount_crystals_per_color_stack, $crystal);
If you look closely, you use a standard assignment with $array = at the beginning of your line. This means, that (like with each variable assignment) the previous value of the variable gets overwritten by the new value provided from the right side of the assignment. What you do not want yet is to overwrite the array, but to append something to it.
This can be done by adding two squared brackets to the end of the variable name: $array[] = .... Now, if the variable $array is really an array, what ever value is on the right side of the assignment will be appended to the array, instead of overwriting it.
Managing result types the right way
The following line still contains a major problem:
$array[] = array_fill(0, $amount_crystals_per_color_stack, $crystal);
The result type of array_fill() is an array itself. By appending it to the previous array, you would get the following structure:
$array = [
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6],
];
As you can see, the code did exactly what it should but not what you wanted. Each result (array) was appended to the array. The result is therefore an array or arrays (or a multidimensional array). What you want instead, is that the values of the result are appended to the existing array.
PHP offers a function for that, named array_merge(). This function takes all elements for one (or more) array(s) and appends them to the end of the first array, that was given to the function. You can use it as followed:
$newCrystals = array_fill(0, $amount_crystals_per_color_stack, $crystal);
$array = array_merge($array, $newCrystals);
As you can see the latter line contains a normal assignment again. ($array =) This is because array_merge() does not modify the first array given to it, but creates a new array with the merged fields. Therefore the new array contains all values from the old one and it is safe to overwrite the old one with it.
The complete code would therefore be:
$array = [];
foreach($crystals_array as $crystal) {
$newCrystals = array_fill(0, $amount_crystals_per_color_stack, $crystal);
$array = array_merge($array, $newCrystals);
}
As I understood the problem
$crystals_array = [2,3,4,5,6];
$amount_crystals_per_color_stack = 2;
$res = [];
foreach($crystals_array as $v) {
// repeat each item from array $amount_crystals_per_color_stack times
$res = array_merge($res, array_fill(0, $amount_crystals_per_color_stack, $v));
}
print_r($res); // [2,2,3,3,4,4,5,5,6,6]
You need to merge your array at each iteration of the loop (repl online) or you lose the result each time.
Like:
$array = array();
for($i = 0; $i < count($amount_crystals_color); $i++)
{
$array = array_merge($array, array_fill(0, $amount_crystals_per_color_stack, $crystals_array[$i]);
}
Also you don't need the $i++ in the loop, because it iterate twice otherwise, and you don't need count(..)-1 if the condition is < instead of <=.
You could use simple foreach() to achieve this-
$amount_crystals_per_color_stack = 2;
$array = [2,3,4,5,6];
$result = array();
foreach($array as $a){
for($i=1;$i<=$amount_crystals_per_color_stack;$i++){
array_push($result, $a);
}
}
print_r($result);

Vigenère table in PHP

I am trying to make a Vigenère table using PHP. My goal is to make a big array with 26 smaller arrays in it like this:
$bigarray = [['a'-'z']['b'-'a']...['y'-'x']['z'-'y']];
I'm thinking of making the first array using the range() function, append that in the big array, then use a for loop to take the first letter, place that letter at the end and make that array append in a big array x25
$letterarray = range('a','z');
array_merge($bigarray, $firstarray);
for ($idx = 0; $idx < 26; $idx++) {
$letterarray = /* Take first letter from $letterarray, put that letter in the end. */
$bigarray = /* Put the $letterarray into the $bigarray. */
I don't know if I need to use the array_splice() or array_slice() function. I also don't know how to put the small array into the big array while keeping the 'array in array' form, because array_merge() just shoves every value into one array.
Your approach is solid. To execute, you just need to copy the previous array, and then use array_shift and array_push to "cycle" it.
$bigarray = [range('a','z')];
for( $i=1; $i<26; $i++) {
// $i=1 because we already have the first one.
$copy = $bigarray[$i-1]; // get most recent entry
array_push($copy,array_shift($copy));
$bigarray[$i] = $copy;
}
Thanks for your comment, after I wrote this thread I figured out a way myself.
$bigarray = array();
$alphas = range('a', 'z');
$bigarray[0] = $alphas;
for ($idx = 1; $idx <= 25; $idx++) {
$firstletter = $alphas[0];
$alphas = array_slice($alphas,1);
array_push($alphas, $firstletter);
$bigarray[$idx] = $alphas;
}
It stores the first letter of the [a-z] array ($alphas) in the variable $firstletter, slices the $alphas array and pushes the element in the $firstletter varible at the end and stores the new array [b-a] into the $bigarray.
The neat thing is that array_slice just changes the indices automatically.
Thanks for the comment :)
-Ed

How can I remove duplicated lines in a file using PHP (including the "original' one)?

Well, my question is very simple, but I didn't find the proper answer in nowhere. What I need is to find a way that reads a .txt file, and if there's a duplicated line, remove ALL of them, not preserving one. For example, in a .txt contains the following:
1234
1233
1232
1234
The output should be:
1233
1232
Because the code has to delete the duplicated line, all of them. I searched all the web, but it always point to answers that removes duplicated lines but preserve one of them, like this, this or that.
I'm afraid that the only way to do this is to read the x line and check the whole .txt, if it finds an equal result, delete, and delete the x line too. If not, change to the next line. But the .txt file I'm checking has 50 milions lines (~900Mb), I don't know how much memory I need to do this kind of task, so I appreciate some help here.
Read the file line by line, and use the line contents as the key of an associative array whose values are a count of the number of times the line appears. After you're done, write out all the lines whose value is only 1. This will require as much memory as all the unique lines.
$lines = array();
$fd = fopen("inputfile.txdt", "r");
while ($line = fgets($fd)) {
$line = rtrim($line, "\r\n"); // ignore the newline
if (array_key_exists($line, $lines)) {
$lines[$line]++;
} else {
$lines[$line] = 1;
}
}
fclose($fd);
$fd = fopen("outputfile.txt", "w");
foreach ($lines as $line => $count) {
if ($count == 1) {
fputs($fd, "$line" . PHP_EOL); // add the newlines back
}
}
I doubt there is one and only one function that does all of what you want to do. So, this breaks it down into steps...
First, can we load a file directly into an array? See the documentation for the file command
$lines = file('mytextfile.txt');
Now, I have all of the lines in an array. I want to count how many of each entry I have. See the documentation for the array_count_values command.
$counts = array_count_values($lines);
Now, I can easily loop through the array and delete any entries where the count>1
foreach($counts as $value=>$cnt)
if($cnt>1)
unset($counts[$value]);
Now, I can turn the array keys (which are the values) into an array.
$nondupes = array_keys($counts);
Finally, I can write the contents out to a file.
file_put_contents('myoutputfile.txt', $nondupes);
I think I have a solution far more elegant:
$array = array('1', '1', '2', '2', '3', '4'); // array with some unique values, some not unique
$array_count_result = array_count_values($array); // count values occurences
$result = array_keys(array_filter($array_count_result, function ($value) { return ($value == 1); })); // filter and isolate only unique values
print_r($result);
gives:
Array
(
[0] => 3
[1] => 4
)

Output only csv lines if column increment is 2

I have a csv file that I would like to filter. The output I need would be only to output the lines if the increment is not equal to 2. In the csv file below, I would like to compare the first line with the second line, if the increment is 2, check line 3 vs line 2, and so on. If the increment is not equal to 2, output the line. I'm looking at the 3rd cloumn values
L1,is,2.0,mins,LATE,for,Arrive,at,shop,18:07:46
L1,is,4.0,mins,LATE,for,Arrive,at,shop,18:09:46
L1,is,6.0,mins,LATE,for,Arrive,at,shop,18:11:46
L1,is,8.0,mins,LATE,for,Arrive,at,shop,18:13:46
L1,is,10.0,mins,LATE,for,Arrive,at,shop,18:15:46
L1,is,2.0,mins,LATE,for,Arrive,at,shop,18:19:49
L1,is,4.0,mins,LATE,for,Arrive,at,shop,18:21:49
L1,is,6.0,mins,LATE,for,Arrive,at,shop,18:23:49
L1,is,8.0,mins,LATE,for,Arrive,at,shop,18:25:49
L1,is,10.0,mins,LATE,for,Arrive,at,shop,18:27:49
L1,is,16.2,mins,LATE,for,Arrive,at,shop,18:34:02
L1,is,18.2,mins,LATE,for,Arrive,at,shop,18:36:02
L1,is,20.2,mins,LATE,for,Arrive,at,shop,18:38:02
L1,is,2.0,mins,LATE,for,Arrive,at,bridge,21:45:26
L1,is,4.0,mins,LATE,for,Arrive,at,bridge,21:47:26
L1,is,6.0,mins,LATE,for,Arrive,at,bridge,21:49:26
So only lines 5,10,13 and 16 would output to page.
I'm stuck on this and would appreciate any help or direction on where to look.
Thanks
If your file is not too big, you can load it into memory directly, like this:
$data = array_map(function($row)
{
return explode(',', $row);
}, file('/path/to/file.csv', FILE_IGNORE_NEW_LINES));
$result = [];
$increment = 2;
$delta = 1E-13;
for($i=1; $i<count($data); $i++)
{
if(abs($data[$i][2]-$data[$i-1][2]-$increment)>$delta)
{
$result[$i] = $data[$i];
}
}
-since your column holds floats, safe comparison on equality will be using precision delta.
Your data will be gathered in $result array, so you can output it like
foreach($result as $row)
{
echo(join(',', $row).PHP_EOL);
}
-or, else, do not store rows inside $result array (if you will need them no longer) and use first cycle to output your rows.
Edit:
Sample above will work in PHP>=5.4 For PHP 5.3 you should replace array definition to
$result = array();
and if you have even older PHP version, like 5.2, then callback inside array_map() should be rewritten with using create_function()

Which is the best way to remove middle element of associative array in PHP?

Please tell me which is the best way to unset middle element of associative array in PHP?
Suppose I have an array of 10,000 elements and I want to remove middle element of that array, which is efficient way to remove middle element?
$temp = array('name1'=>'value1','name2'=>'value2',...,'name10000'=>'value10000');
$middleElem = ceil(count($temp) / 2);
$i = 0;
foreach ($temp as $key=>$val) {
if ($i == $middleElem) {
unset($temp[$key]);
break;
}
$i++;
}
Is above code efficient way?
Considering $array is your array, this code remove the middle element if it has odd number of elements. If its event it'll remove the first of 2 middle elements.
$i = round(count($array)/2) - 1;
$keys = array_keys($array);
unset ($array[$keys[$i]]);
Test Result: http://ideone.com/wFEM2
The thing you have to figure out is what you want to do when you have an array with an even number of elements. What element do you want to get then?
The above code picks the 'lower' element, the code could easily be edited to make it pick the 'higher' element. The only thing you have to check is (what all others answers failed to do) what happens if you have three elements. It doesn;t pick the middle element, but the last. So you would have to add a check for that then.
$temp = Array("name1"=>"value1","name2"=>"value2",...,"name10000"=>"value10000");
$middleElem = ceil(count($temp)/2);
$keys = array_keys($temp);
$middleKey = $keys[$middleElem];
unset($temp[$middleKey]);
There ^_^
I think it's a proper way to do it. Try this:
array_remove_at( $temp, ceil(count($temp) / 2) - 1);
function array_remove_at(&$array, $index){
if (array_key_exists($index, $array)) {
array_splice($array, $index, 1);
}
}
You can find the size of the array, divide that number by two and then proceed to remove the element. Not sure about the performance isssues about that though
Firstly, I wouldn't worry too much about what is the most efficient way at this point. You're much better off coding for how easy the code is to read, debug and change. Micro-optimisations like this rarely produce great results (as they're often not the biggest bottlenecks).
Having said that, if you want a solution that is easy to read, then how about using array_splice.
$temp = array('name1'=>'value1','name2'=>'value2',...,'name10000'=>'value10000');
$middleElem = ceil(count($temp) / 2);
array_splice( $temp, $middleElem, 1 );
I would take it that the following code is more efficient, because you don't have to execute it in a loop. I generally follow the same pattern as Kolink, but my version checks if there actually is a "middle element". Works on all types of arrays, I think.
<?php
for( $i = 0; $i <= 9; $i ++ ) {
$temp['name'.$i] = 'value'.$i;
}
if( ( $count = count( $temp ) ) % 2 === 0 ) {
/** Only on uneven arrays. */
array_splice( $temp, ( ceil( $count ) / 2 ), 1 );
}
var_dump( $temp );
EDIT: Thavarith seems to be right; array_splice is much faster than simply unsetting the value. Plus, you get the added benefit of not having to use array_keys, as you already now at what $offset the middle is.
Proper way seems to be:
unset(arr[id]);
arr = array_values(arr);
For first removing element at index id and then re-indexing the array arr properly.
unset($myArray[key])
since your array is associative, you can drop any element easily this way

Categories