I'm a newbie and I have a very basic question about PHP arrays
Code:
While(!feof($file_handle))
{
$SecondRow = fgets($file_handle); //gets row
$trimmed = trim($SecondRow); //removes extra bits
$replace = array("'");
$finalstring = str_replace($replace, "_", $trimmed); //Still a string w/o "'"'s
$CleanString = preg_split("/[\s]*[,][\s]*/", $finalstring); //creates the array
//print_r($CleanString);
echo "Row " . $CleanString[1]. "<br/>"; //??????
.....
}//end while
the opened file has the following:
0001,sparta
0005,PURCHASING
...
...
...
Question:
When I echo "Row " . $array[0], I get the first column as expected. But when I echo "Row " . $array[1], I get an the "Undefined offset: 1" error. When the string is read into the array (via preg_split) aren't both
array[0]->0001 and array[1]->sparta set?
thanks.
Looking at your entire code, you're essentially replicating a native function like fgetcsv() or one of it's equivalents.
Just pick one and be done :)
As far as determining how to use the array, as noted in the comments use print_r or var_dump() to guide you. Also read up on PHP Arrays
This is because fgets() get one row at time (one row per "loop").
Related
The code below is working in reading per row and count each identical appearances. However, I still need excel to sort per row left to right before I i save it as delimited by as text file. Right now I want to omit the excel step. I checked on php manual and saw the sort and explode functions. I inserted those command but its not working. Can someone help me point to the right direction ?
raw data is :
hero2,hero1,hero3
hero2,hero3,hero4
hero1,hero2,hero3
text file db after excel :
hero1,hero2,hero3
hero2,hero3,hero4
hero1,hero2,hero3
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
Code :
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sort ($lines);
$result = array_count_values($lines);
foreach($result as $v => $amount)
echo "Appeared " . $amount . "x: " . $v . "<br />";
?>
After reading the suggestions and samples of those who answered I came up with this code now.
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", implode($data));
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "\n";
}
?>
however the ouput became like this
output :
appeared 3x: hero2
appeared 3x: hero3
appeared 2x: hero1
appeared 1x: hero4
correct output should be like this
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
I believe your problem is you are using explode with a space and you should be using it with a comma. explode(",",$data);
I'm thinking you then also want to turn your data back into a string before you try and count them or I don't think you'll get the results you're expecting.
For example...
$sortedString = implode(",", $theArray);
You are looping over the old data before doing the sort. And you are not using a PHP function sort, you are instead making it a kind of a variable (remove the $ before it).
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($sorted_lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "<br />";
}
?>
<?php
// Open the file
$filename = 'pvemail.txt';
$fp = fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
//print_r ($array);
for ($c = 0; $c < count($array); $c++){
$cell = explode(",", $array[$c]);
print_r ($cell);
echo '<br/>';
}
?>
I am currently working on this code. I have taken a text file generated from a Google report, and managed to explode it into an array, and then I've taken each element of the array and exploded that into another array. However, the problem I'm now having is I only want to retrieve 3 elements of the second exploded array and there are 20 elements to each array.
What would be the best way to go about this, should I use a for or foreach loop? I only need to print $cell[2], $cell[11] and $cell[12]. I have tried using:
echo ($cell[2] + " " + $cell[12] + " " + $cell[11]
($cell[11] and $cell[12] are in this order because 11 is a last name and 12 is a first name and I want the first name first so I've had to put them backwards) but when I run that piece of code it just outputs line breaks and 0's. I'm really just wondering what would be the most effective method of looping through the arrays, and should I do it within the loop that I have already established?
I was thinking that if I were to put it inside my existing for loop I could use an if/else loop, something like:
if($cell = $cell[2]){
echo ($cell[2])
};
but i'm not convinced this will work. Should I define a variable to store $cell[2], [11] and [12] in, and create my if loop based on that, and then I would only need to echo the variable? Is that likely to be effective? Any help would be appreciated, I've looked around on the forum for posts similar to this but I haven't been able to find anything.
20130912,b875c9b154cf7b8d,el#pv-eu.com,ACTIVE,30720,1054180015,,,20100902,20130910,20130904,L,E,,,,20130911,2010-09-02 09:11:37,2013-09-10 23:51:21,2013-09-04 03:06:09,2013-09-11 00:41:24
20130912,66c63753b8188f17,lf#pv-eu.com,ACTIVE,30720,3699701524,,,20110315,20130911,20130911,F,L,,,,19691231,2011-03-15 02:00:31,2013-09-11 00:50:17,2013-09-11 00:52:16,1969-12-31 16:00:00
20130912,bd5ef40689adf9ac,ah#pv-eu.com,ACTIVE,30720,3476851137,,,20110426,20130911,20130910,H,A,,,,20110720,2011-04-26 01:47:56,2013-09-11 16:58:48,2013-09-10 06:20:26,2011-07-20
This is how the text file itself looks, although there is a lot more data. All I'm trying to pull is the email address and name.
Assuming pvemail.txt is a CSV file, does this solve your problem?
$content = file_get_contents('pvemail.txt');
$lines = explode("\n", $content);
header('Content-type: text/plain');
foreach($lines as $line) {
$values = explode(',', $line);
echo $values[2], ' ', $values[12], ' ', $values[11], "\n";
}
Using the 3 sample lines, the above code outputs this:
el#pv-eu.com E L
lf#pv-eu.com L F
ah#pv-eu.com A H
I'm working on a php function that will compare the components of two arrays. Each value in the arrays are only one english word long. No spaces. No characters.
Array #1: a list of the most commonly used words in the english
language. $common_words_array
Array #2: a user-generated sentence, converted to lowercase, stripped
of punctuation, and exploded() using the space (" ") as a delimiter.
$study_array
There's also a $com_study array, which is used in this case to keep
track of the order of commonly used words which get replaced in the
$study_array by a "_" character.
Using nested for loops, what SHOULD happen is that the script should compare each value in Array #2 to each value in Array #1. When it finds a match (aka. a commonly used english word), it will do some other magic that's irrelevant to the current problem.
As of right now, PHP doesn't recognize when two array string values are equivalent. I'm adding in the code to the problematic function here for reference. I've added in a lot of unnecessary echo commands in order to localize the problem to the if statement.
Can anybody see something that I've missed? The same algorithm worked perfectly in Python.
function create_question($study_array, $com_study, $common_words_array)
{
for ($study=0; $study<count($study_array); $study++)
{
echo count($study_array)." total in study_array<br>";
echo "study is ".$study."<br>";
for ($common=0; $common<count($common_words_array); $common++)
{
echo count($common_words_array)." total in common_words_array<br>";
echo "common is ".$common."<br>";
echo "-----<br>";
echo $study_array[$study]." is the study list word<br>";
echo $common_words_array[$common]." is the common word<br>";
echo "-----<br>";
// The issue happens right here.
if ($study_array[$study] == $common_words_array[$common])
{
array_push($com_study, $study_array[$study]);
$study_array[$study] = "_";
print_r($com_study);
print_r($study_array);
}
}
}
$create_question_return_array = array();
$create_question_return_array[0] = $study_array;
$create_question_return_array[1] = $com_study;
return $create_question_return_array;
}
EDIT: At the suggestion of you amazing coders, I've updated the if statement to be much more simple for purposes of debugging. See below. Still having the same issue of not activating the if statement.
if (strcmp($study_array[$study],$common_words_array[$common])==0)
{
echo "match found";
//array_push($com_study, $study_array[$study]);
//$study_array[$study] = "_";
//print_r($com_study);
//print_r($study_array);
}
EDIT: At bansi's request, here's the main interface snippet where I'm calling the function.
$testarray = array();
$string = "This is a string";
$testarray = create_study_string_array($string);
$testarray = create_question($testarray, $matching, $common_words_array);
As for the result, I'm just getting a blank screen. I would expect to have the simplified echo statement output "match found" to the screen, but that's not happening.
(EDIT) make sure your that your splitting function removes excess whitespace (e.g. preg_split("\\s+", $input)) and that the input is normalized properly (lowercase'd, special chars stripped out, etc.).
On mobile and can't seem to copy text. You forgot a dollar sign when accessing the study array in your push command.
change
array_push($com_study, $study_array[study]);
to
array_push($com_study, $study_array[$study]);
// You missed a $ ^ here
Edit:
The following code outputs 3 'match found'. i don't know the values of $common_words_array and $matching, so i used some arbitrary values, also instead of using function create_study_string_array i just used explode. still confused, can't figure out what exactly you are trying to achieve.
<?php
$testarray = array ();
$string = "this is a string";
$testarray = explode ( ' ', $string );
$common_words_array = array (
'is',
'a',
'this'
);
$matching = array (
'a',
'and',
'this'
);
$testarray = create_question ( $testarray, $matching, $common_words_array );
function create_question($study_array, $com_study, $common_words_array) {
echo count ( $study_array ) . " total in study_array<br>";
echo count ( $common_words_array ) . " total in common_words_array<br>";
for($study = 0; $study < count ( $study_array ); $study ++) {
// echo "study is " . $study . "<br>";
for($common = 0; $common < count ( $common_words_array ); $common ++) {
// The issue happens right here.
if (strcmp ( $study_array [$study], $common_words_array [$common] ) == 0) {
echo "match found";
}
}
}
$create_question_return_array = array ();
$create_question_return_array [0] = $study_array;
$create_question_return_array [1] = $com_study;
return $create_question_return_array;
}
?>
Output:
4 total in study_array
3 total in common_words_array
match foundmatch foundmatch found
Use === instead of ==
if ($study_array[$study] === $common_words_array[$common])
OR even better use strcmp
if (strcmp($study_array[$study],$common_words_array[$common])==0)
Use built-in functions wherever possible to avoid unnecessary code and typos. Also, providing sample inputs would be helpful too.
$study_array = array("a", "cat", "sat", "on","the","mat");
$common_words_array = array('the','a');
$matching_words = array();
foreach($study_array as $study_word_index=>$study_word){
if(in_array($study_word, $common_words_array)){
$matching_words[] = $study_word;
$study_array[$study_word_index] = "_";
//do something with matching words
}
}
print_r($study_array);
print_r($matching_words);
I have a PHP script that returns an array of numbers:
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
echo $filedata[5];
result:
0.23387718200684
3.6163940429688
0.030826568603516
Is there a way to get the script to return results added up as just one number?
echo array_sum($filedata);
I think that should do the trick.
Take a look here for further information. array_sum just sums up all the values in an array.
EDIT
The above example would work if your array was a flat array of integers, decimals etc. The following is how you would sum up a 2 dimensional array where the value you want to sum is at index position 5:
var $sum = 0;
foreach($filedata as $dataElement) {
$sum += $dataElement[5];
}
echo $sum;
The above code assume that $filedata is an array of array's, each array in filedata has a value at index 5 that can be summed up... Is that more along the lines of what you need?
You could use array_sum:
echo array_sum($filedata);
Not working?
As might be your case $filedata[5] actually contains a string with newlines and numbers. In this case you need some extra code. Important is the line endings - these can be different depending on your operating system / file.
$sum = 0;
$sLineEnding = "\r\n";
foreach($filedata as $data)
{
$parts = explode($sLineEnding, $data);
$sum += array_sum($parts);
}
echo $sum;
As I see in your code, you are executing it in command line and you do echo $filedata[5] an you get different lines, this is because you are not paying attention to '\n' character, so what you need is to change that character somehow...
there are different ways... In this example I'm changing the "\n" for " " simple space
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
// if "\n" is not working try '\n'
// One way
echo str_replace(" ","\n",$filedata[5]);
// Another way
echo implode(" ", explode("\n", $filedata[5]));
i was wondering how i can use php to access text files and display the information using php arrays, this might seem like a newbie question, but i havent worked with external files.
so here goes.
home.txt:
ha15rs,250,home2.gif,2
ha36gs,150,home3.gif,1
ha27se,300,home4.gif,4
ha4678,200,home5.gif,5
what i wanted to do is sort this information in a html table, with each line as a row and 4 coloumns to represent the data!! thanks cheers :))
Looks like comma separated values. See the examples at http://ee.php.net/manual/en/function.fgetcsv.php
you can do something like that :
<?php
$file = file_get_content('file.txt');
$array = explode("\n", $file);
Notice that it depend of your newline type :
typically:
Gnu/Linux / Unix / MacOS since X use "\n"
Windows use "\r\n"
MacOS before X use "\r"
you should look at the file() function too, it reads the file into an array line by line.
after that you can seperate the values with explode().
<?php
$foo = file('example.txt');
// will echo the 2nd line of the example.txt-file
echo $foo[1];
// echos all items seperated by a comma
foreach($foo as $line=>$values){
$value_arr = explode(',',$values);
echo 'line #'.$line.': ';
foreach($value_arr as $id=>$item){
echo $id.': '.$item.'; ';
}
echo "\n";
}
?>
a start of deal with this :
# echo before table headline
...........
$handle = #fopen("myfile.txt","r");
# read line by line
while (($buffer = fgets($handle, 4096)) !== false) {
echo '<tr>';
$array = explode(',', $buffer);
foreach($array as $val){
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}