While and Array - php

<?php
public function fetchAll($sql){
$result = mysqli_query($connection,$sql);
$out=array();
while($row=mysqli_fetch_assoc($result)){
$out[] = $row;
}
return $out;
}
Here array() has no initial size. can u tell me how this works without any size
2.in while statement we are saving arrays in a non declared variable, without any size too.how this statement works. how long this loop will work.

The code:
$out=array();
only initializes the $out-variable as an array, that is initially empty.
$out[]=$row;
will ADD an item/element into the array, increasing it's size by one on each cycle of the loop. Loop will run as many times as there are rows in your sql-result. Please read array_push documentation to fully understand this shorthand.

Related

PHP in_array not working properly?

I'm working on in_array() method. If the value read is already in the array it should be skipped and proceed to the next value. If the current value is not on the array yet, it should be pushed to the array.
here's my code:
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$Res_Array = array();
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Problem: It seems that it ignores my condition which is if(in_array($SQL_Result_Time, $Res_Array, true)){break; } and still inserts the value into the array. It still duplicates data
Question:
How to prevent the duplication data where if the current value was found inside the array it would just skip the statement and proceed to another value for checking the array and so on?
Is my logic on checking the value on the array is right?
You are re-initialising your array on every iteration of the while loop. You should declare it outside of the loop:
$Res_Array = array();
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Also, as mentioned by Marvin Fischer in his answer, your break statement will terminate the while loop on the first duplicated value. You should instead use continue
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
...
if(in_array($SQL_Result_Time, $Res_Array, true)){
continue;
}
....
}
This question should clarify any issues you have with break and continue statements
First of all, inside of a loop you should use continue, otherwise you cancel the whole loop, secondly you empty $Res_Array at the beginning of every loop purging the old data, inserting the new one and echoing it again

Select only arrays for foreach

I've got a foreach statement that on an item that has both objects and arrays in it.
foreach($result as $data)
that contains both arrays and objects. how do i specify the foreach to only select to loop through one or the other? when it loops through them all it takes forever
I had tried foreach($result->data as $data) but then it errors on the arrays telling me it is trying to get property of an object, which is understandable. once I add an if statement to check if the first result is an object it almost triples the script run time since there are so many results.
Well you could just use is_object() and is_array() (both return a boolean):
if (is_object($var)) {
// do something
} else if (is_array($var)) {
// well then, do something else
}

PHP While loop only echoes once

this is the PHP code i have:
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
while ($row2 = mysql_fetch_object($query2)) {
echo "%".$row2->id."%";
}
}
I want it to output for example: *1*%1%%2%%3%%4%*2*%1%%2%%3%%4%*3*%1%%2%%3%%4%
But what this loop outputs is: *1*%1%%2%%3%%4%*2**3*
(It only outputs the $row2 values in the first loop of $row1.
How can I fix this? Thanks.
A few things to note about mysql_fetch_object(). From the PHP document:
Warning: This extension is deprecated as of PHP 5.5.0
Please note above.
returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.
Please note what I bolded.
The $result object (in your code this would be $query2) is an iterative object that has a pointer pointing to the current item.
Current Item
|
v
[1][2][3][4]
When your first loop hits your second loop, it iterates over the whole thing, such that at the end, the object now looks something like this:
Current Item
|
v
[1][2][3][4]
For each iteration of the first loop, after the first time, the mysql_fetch_object() function basically goes like this:
mysql_fetch_object() ~
1. Get the next time
2. Uh, there are no more objects because we're at item [4]. Return done.
So, how do you get it to work? You could simply save the results into an array and then iterate over that array or you can reset the pointer with mysql_data_seek() (which is also deprecated as of 5.5).
To reset the data pointer, it would be something like this:
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
while ($row2 = mysql_fetch_object($query2)) {
echo "%".$row2->id."%";
}
// put the result pointer back to the front
mysql_data_seek($query2, 0)
}
Note1, This SO question/answer helped me find the function to use to reset the pointer.
Note, the downside is that you're calling a function that's creating an object, which creates processing overhead every time it runs.
The other option would be save the results into an array and just loop through the array every time:
$secondary_result = array();
while ($row2 = mysql_fetch_object($query2)) {
$secondary_result[] = $row2;
}
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
foreach($secondary_result as $row2) {
echo "%".$row2->id."%";
}
}
Note, this method will be creating extra memory usage of storing the objects in an array, but it would save on CPU processing as you're not re-creating the objects over and over again, as well as calling a function.
If you just print output, you can consider just saving the result first. No matter now many times you loop over $secondary_result, the final result will always be the same (as per your code, the first loop shows no signs of being directly influencing the second result).
In that case, this makes much more sense
$buffer = '';
while ($row2 = mysql_fetch_object($query2)) {
$buffer .= "%".$row2->id."%";
}
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
echo $buffer;
}
but I really don't know why you'd do that. If you're doing a nested loop, usually it's because the result of the first loop is affecting the second loop.
But I hope that helps!
Cheers!
EDIT
Per #Blazemonger's comment about looking ahead, the PDO equivalent would be: MySqli:Fetch-Object
When you have a result object from using the PDO function, you would loop like this:
while($row1 = $query1->fetch_object()) {
echo "*".$row1->id."*";
while ($row2 = $query1->fetch_object()) {
echo "%".$row2->id."%";
}
// put the result pointer back to the front
$query2->data_seek(0);
}
The above example shows both the fetch Object and pointer reset versions of MySqli.
The problem is that once you iterate fully through $query2, that's the end of your results. The next time through your $row1 loop, you're still at the end of $query2 and have no results left. Try using mysql_data_seek to go back to the start of your results:
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
mysql_data_seek($query2, 0);
while ($row2 = mysql_fetch_object($query2)) {
echo "%".$row2->id."%";
}
}
if you really need to repeat your second query data many times, get it into array first, and loop over this array as many times as you need.
First of all: The mysql_* functions are deprecated and will be removed in PHP 5.5. Consider using mysqli or PDO instead.
That being said; back to your question:
Each result set contains an internal pointer to one of the records in the result set. Initially, this pointer points to the first record, and is advanced with each call to mysql_fetch_object.
After your first inner loop, the internal pointer of the $query2 result set will already be at the end of the list, so subsequent calls to mysql_fetch_object will only return FALSE.
If your inner query depends on values from $row1, you will need to re-execute the second query within your outer loop. Otherwise, you can reset the result pointer with mysql_data_seek.
Perhaps you're not getting anything when you call $row2 = mysql_fetch_object($query2) which would give you the output you're getting.
After the first loop there are no more results for query2 to return. So the while is false in each additional loop. You would want to reset the query with mysqli_data_seek or storing all the data in a separate array and looping through that instead.
Please also note:
Per the documentation http://us2.php.net/manual/en/function.mysql-fetch-object.php
The mysql extension is deprecated as of PHP 5.5.0, and will be removed
in the future. Instead, the MySQLi or PDO_MySQL extension should be
used

Foreach only taking the first value from Array

I have the following code:
$referrals = inputFilter($_POST['referralsIds']);
$array =explode(",",$referrals);
foreach($array as $key=>$value):
/
$s=mysql_query("SELECT * FROM users WHERE upline='".$userdata['id']."' AND id='$value'");
$num_rows=mysql_num_rows($s);
if($num_rows==0)
return 2;
// No error found and the update was succesful - Return success!
mysql_query("UPDATE users SET upline='' WHERE id='$value'");
mysql_query("UPDATE users SET rbalance=rbalance-".$sdata['direct_delete_fee'].", direct_referrals=direct_referrals-1 WHERE username='".$userdata['username']."'");
return 100;
endforeach;
The $referrals variable is posting two values (10,11).But when I put it in a foreach loop, it will only run the query with the first value (10). How to do so it run through ALL values submitted?
Thanks.
You have a return 100 inside your for loop. It's terminating the loop on its first iteration.
return statements terminate the enclosing function. If you need to return multiple results, consider pushing them onto an array and then returning the array once you're done.
You have code returning before the end of your for each
return 100; //HERE
endforeach;
You probably want:
endforeach;
return 100;
So you have two values, then you explode it ? :O But i think you meant $array.
You have return 100 which will return from the function, and as well from foreach.
You are returning 100 from whatever function you're in on the first iteration of the loop. returning will cause the loop to stop immediately.

Foreach() value is set, after value disappears

I am trying to add a new key to an existing numerical indexed array using a foreach() loop.
I wrote this piece of code:
foreach($new['WidgetInstanceSetting'] as $row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
The first debug() works as I expected: the 'random_key' is created in the $new array.
Now, the problem is that the second debug() shows the $new array, but without the newly added key.
Why is this happening? How can I solve this problem?
$row ends up being a copy in the scope of the foreach block, so you really are modifying a copy of it and not what's in the original array at all.
Stick a & in your foreach to modify the $row array within your $new array by reference:
foreach($new['WidgetInstanceSetting'] as &$row){
And as user576875 says, delete the reference to $row in case you use that variable again to avoid unwanted behavior, because PHP leaves it around:
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
unset($row);
debug($new);
Use the & to get a by reference value that you can change.
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
You need to access the element by reference if you want to modify if within the array, as follows:
foreach($new['WidgetInstanceSetting'] as &$row) {
$row['random_key'] = $this->__str_rand(32, 'alphanum');
}
you are not creating random_key in $new array you are creating it in $row

Categories