php - how come I cant get each arrays elements in an array if i read it in txt file?
Get the solution ↓↓↓says the orders.txt contains
hello
hello
hello
Code:
<?php
$orders = file("orders.txt");
$row_count = count($orders);
for ($row = 0; $row < $row_count; $row++) {
$col_count = count($orders[$row]);
for ($col = 0; $col < $col_count; $col++) {
echo $orders[$row][$col];
}
}
?>
I found that the cause of error here is thatcount($orders[$row])
didn't return the total number of element in this array.
the text files in .txt are multidimensional array right?
If i create a multidimensional array I can get each arrays element count in the multidimensional array by using count()
but here im reading from the .txt file and I think it is multidimensional array
My question:
I get the rows count, but not the column count.
I know i can dostrlen($orders[$row])
instead, but whycount($orders[$row])
is not possible.
Answer
Solution:
What are you trying to achieve. Your example orders.txt is too simple, and you don't specify the result that you expect. file() returns an array of strings where each string is a line from the file (http://php.net/manual/en/function.file.php).
Perhaps if you are trying to read multiple values from each line (i.e. read each line as an array) you should use fgetcsv() instead (http://php.net/manual/en/function.file.php).
Answer
Solution:
When I check print_r($orders), the data from the txt is not stored in a multidimensional array but just a plain array with key/val. So you're assumption is not correct. I'm having a hard time understanding exactly what the problem is (language barriers ...). Your col count is correct as well, since there's only 1 value inside (I get 1 here).
It probably returns 4 (it should be 3) because you have an extra line-feed character in the txt file, remove that last empty line and it will make sense.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: mysqli::real_connect(): (hy000/2002): connection refused
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.