I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file.
Everything works, except I can't get it to remove the middle space. For example:
list1.txt:
1
2
list2.txt:
dog
cat
The result I get is:
dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat
But I need (see spaces):
dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat
Code:
<?php
$array1 = file('list1.txt');
$array2 = file('list2.txt');
$array3 = array();
$array4 = array();
foreach ($array1 as $key1)
{
foreach ($array2 as $key2)
{
$array3[] = $key1 . $key2;
{
$array4[] = $key2 . $key1;
}
}
}
print_r($array3);
print_r($array4);
$fp = fopen('combined.csv', 'w');
fputcsv($fp, $array3);
fputcsv($fp, $array4);
fclose($fp);
?>
Thanks to the help from Rizier123, I solved the problem by simply changing lines 3 and 4 as follows:
$array1 = file('list1.txt', FILE_IGNORE_NEW_LINES);
$array2 = file('list2.txt', FILE_IGNORE_NEW_LINES);
The problem was due to the line breaks in my two list files, as each keyword used in the arrays are on a separate line.
Use the below code
foreach ($array1 as $key1){
foreach ($array2 as $key2){
$array3[] = trim($key1).trim($key2);
$array4[] = trim($key2).trim($key1);
}
}
Or Use array_map function to trim all the elements of an array
$array = array_map('trim', $array);
As Ravinder and Rizier stated, use trim(). So for example:
<?php
$array1 = file('list1.txt');
$array2 = file('list2.txt');
$array3 = array();
$array4 = array();
foreach ($array1 as $key1)
{
foreach ($array2 as $key2)
{
$array3[] = trim($key1) . trim($key2);
$array4[] = trim($key2) . trim($key1);
}
}
print_r($array3);
print_r($array4);
$fp = fopen('combined.csv', 'w');
fputcsv($fp, $array3);
fputcsv($fp, $array4);
fclose($fp);
?>
As a side note, it looks like you have a couple stray {
and }
in your code. You'll need to remove those for the code to complete successfully.
Try this foreach
loop instead:
foreach ($array1 as $key1)
{
foreach ($array2 as $key2)
{
$key1 = trim($key1);
$key2 = trim($key2);
/*
If the above doesn't work, try this method:
(If you use this method, you should delete your $array3 and $array4 assignments)
$arrangement['array3'] = $key1.$key2;
$arrangement2['array4'] = $key2.$key1;
foreach($arrangements as $arrayName=>$str) {
$str = preg_replace('#^([^ ]+) ([^ ]+)$#', '', $str);
$$arrayName[] = $str;
}
*/
$array3[] = $key1 . $key2;
{
$array4[] = $key2 . $key1;
}
}
}