Php scope: array value cannot be accessed outside of loop - php

My code:
<?php
$file="./Speed10.txt";
$document=file_get_contents($file);
$rows = explode ('(', $document);
$a[$r][$c];
for($r=0; $r<9103; $r++){ //1903 rows in text file
$a[$r][$c]; // Array declared here - doesnt solve problem
for($c=0; $c<103; $c++){
//$a[$r][$c] = rand();
// print_r($a[$r][$c]);
}
}
foreach ($rows as $ri => $row) {
$a[$ri][$c] = explode (';', $row);
//XXXXXXXXXXXXX
}
print_r($a[1][$c]); // NOT PRINTING*
?>
I have a 2D array as you can see above, it divides a text file into rows and columns.
That part works perfectly, but I try to print out all the cells of one row, it isn't printing.
However, if I move the print_r line to where the X's are, it works (although its being printed out in a loop). Sounds like a scope problem to me but I can't figure out what. I tried initialising the array as a global variable but that didn't fix it.

At the end your script, executed "as is", $c will be 103 but elements in $a[1] will only be set from 0 to 102.
So your accessing a non-existant index, hence it prints nothing.
I have created a slightly modified example which clearly shows the problem.
Notice: Undefined offset: 103 in [...][...] on line 15

Related

Foreach returns only first record, stops

This should be very simple, but I'm getting odd behavior I've never seen before. Here is the code:
<?php
$csv = array_map('str_getcsv',file('dummy.csv'));
$n=1;
foreach($csv as $key=>$val) {
$sql = "UPDATE table set field = '$val[$key]' WHERE id = $n";
echo $sql."\n";
$n++;
}
?>
The .csv file is 260 simple text phrases that show up properly with print_r($csv);. The above code gives proper output but stops after the first record. Why?
str_getcsv returns an array.
array_map also returns an array.
So, your $csv is an array with an array within it.
After your line $csv = array_map('str_getcsv',file('dummy.csv'));, add the line $csv = $csv[0]; This pulls out the inner array. Then you should get the expected results without changing the remainder of your code.

Undefined offset error in array when count show the number of element inside

As stated in the title, I encounter a strange problem for the following code.
for($i=0; $i < count($maindata) ; $i++){
$currentId = $maindata[$i]['SubmissionId'];
$output = array_filter($subdata, function ($value) use ($currentId)
{ return $subdata['ParentId'] == $currentId; });
echo 'total sub data '.count($output); //output 86
for($j=0; $j < count($output) ; $j++){
echo $output[$j]['SubmissionId']; //Undefined offset Error
}
}
As you can see, I loop through an array. Inside the loop I filter out another array to get the associate data.
And then I echo the count of the filter array and echo the data with another loop. The code was fine for first item and it show data but starting from the second item, it show
Notice: Undefined offset: 0 in myfile on line 79
inside the second loop but the count still showing correct answer also. line 79 is echo $output[$j]['SubmissionId']; //Undefined offset Error .
Please help me to figure out what is the problem. Thanks in advance.
Solution:-
Inside second iteration use this:-
if(isset($output[$j]['SubmissionId'])){echo $output[$j]['SubmissionId'];}
Explanation:-
$output is a filtered sub-array and due to filtration it's quite possible that some indexes are missing
when you did for($j=0; $j < count($output) ; $j++){ and if count($output) is 86 means loop will go for 0-85 (in sequential order)
Now if $output has missed index 3 (for example) then the code $output[$j]['SubmissionId'] will give error
So check that using above code and problem is solved.
2nd opinion:-
you can do like below:-
$output = array_values($output);
echo 'total sub data '.count($output); //output 86
for($j=0; $j < count($output) ; $j++){
echo $output[$j]['SubmissionId'];
}
Note:- this approach will re-index your array and if some-where you are going to use original indexes then this code will lead you to problems.
3rd option(better than 2nd one)
Since foreach() take care of indexes so instead of for() loop use foreach.
Thanks
In first place , i think that "foreach" loop instead of "for" will be more clear and a better practice for what you need.
http://php.net/manual/fr/control-structures.foreach.php
In a second time, do you try to make a var_dump instead of echo to see what structure you have into your array?
for($i=0; $i < count($maindata) ; $i++){
$currentId = $maindata[$i]['SubmissionId'];
$output = array_filter($subdata, function ($value) use ($currentId)
{ return $subdata['ParentId'] == $currentId; });
var_dump($output);exit();
.....
Maybe you don't have SubmissionId sub-index inside.
I found the problem by printing out the array as #Anant mention. At first I thought $output arrary's index will be starting from zero as normal array. But, since I got this from array_filter, the index starting from the end of last filtered array.
So I change the second loop to foreach and problem solved now.
Thank you all!!!

how can i have dynamic name of a array variable in php?

I used this but my array show blank.
foreach($page_data->result() as $text){ $i++;
echo $name="text".$i; //this line print ok.
$$name=array();
echo $$name['content']=$text->$content; //this line print ok.
print_r($text1);
} print_r($text1);
here i am tying to name the array dynamically as text1,text2,text3.......
but when i print $text1 it shows me a blank array.
can any one help me out with this.
It's simply a syntax ambiguity. $$name['content'] is understood as:
${$name['content']}
I.e. the name of the variable is supposed to be the value of $name['content'], which obviously doesn't exist, which actually leads to an error if you'd enable error reporting. You can solve this with:
${$name}['content'] = $text->$content;
However, you really should solve this by using an array instead of variable variables:
$texts[] = array('content' => $text->$content);
You're incrementing the index before you echo the contents of the variable, so if you only have 1 result, it will try and access an undefined index, you are also re initialising the name array every time you pass through the loop, you should not do this
Results
------------------
Num Content
0 I am a text post
If these were the results returned and you wanted to point to index i, then when your loop goes through this would happen:
i = 0;
i = 1;
assign values to name array
As there is only one result this would then happen
Results
------------------
Num Content
0 I am a text post
- - <----- i = 1 (null pointer exception?)
This would be why no values are showing in your array, try change your code to this:
// Declare i to point at the 0 index
$i = 0;
$name=array();
foreach($page_data->result() as $text){
$name[i]['content']=$text;
$i++;
}
Your name array will no add the text content to a new index with each pass of the loop, i.e. if you had 2 results
$name[0]['content'] = "This is a text post";
$name[1]['content'] = "Here is another post";
Hope this helps.

how come I cant get each arrays elements in an array if i read it in txt file?

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 that count($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 do strlen($orders[$row]) instead, but why count($orders[$row]) is not possible.
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).
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.

PHP foreach() is amending the array

The following code which is displaying a value from within an array is presenting different results when wrapped in a foreach() as opposed to when I use a simple for-loop. The for-loop is presenting the correct data but the foreach() appears to be amending the input array with every iteration.
$arr = array_merge($arr1, $arr2);
for ($x = 0; $x < count($arr); $x++) {
echo $arr[90]['circread_value'];
}
foreach ($arr as $unused) {
echo $arr[90]['circread_value'];
}
The output from the for-loop is the same value over and over again (as expected):
1382429.00
1382429.00
1382429.00
1382429.00
...
The output from the foreach() shows that the 91st element in the array is changing with each iteration:
56256.00
45652.00
50726.00
317896.00
...
How can this be?
Note: I know the code above is contrived (obviously within the foreach() I'm actually wanting to do further processing and refer to each element of the array that I'm iterating through, not just look at the 91st element.) I have simply pared back the code to something simple (as part of my debugging, as much as for posting here!)
Some further information:
$arr has been created by array_merge'ing two 91-element arrays to create a 182 element array.
The behaviour I see is only happening for the 91st element - if I echo out $arr[89]['circread_value'] or $arr[91]['circread_value'], I get consistent values from the foreach() too.
The (seemingly random) values that I see in the foreach() are actually values from other elements in the array (the array as it looks prior to beginning the foreach)
The input arrays ($arr1 and $arr2) can be found here: http://pastebin.com/wQN8XXu2
Thanks for any insight. Don't hesitate to ask for further information.
foreach modifies the internal array pointer, for doesn't, because it expects you to supply an integer offset, as evidenced here http://us3.php.net/manual/en/control-structures.foreach.php
"As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior."
There is something wrong with your code brother.
I've just tested this:
$arr = array(
0 => array('blah' => 123.42),
1 => array('blah' => 5488.87),
90 => array('blah' => 669874.923)
);
for ($x = 0; $x < count($arr); $x++) {
echo $arr[90]['blah'] . PHP_EOL;
}
foreach ($arr as $unused) {
echo $arr[90]['blah'] . PHP_EOL;
}
And it outputs fine:
669874.923
669874.923
669874.923
669874.923
669874.923
669874.923
Do you mind showing us a little more of your code?
Problem found. That 91st element of the array was actually a reference to the array. The foreach was then using the same variable name (reference to the same array - named $unused in the example snippet I gave in the question) so both were looking at the same array.
We noticed the "&" in the array dump after posting it on here for you guys, so StackOverflow has helped our debug process... thanks for everyone's input.

Categories