A while loop usually has code that tries to avoid an infinite loop. I don't understand how this works while($row = mysqli_fetch_array($result_set)?
From the php manual, it says that mysqli_fetch_array returns an array per result row. So we are assigning here an array to the variable $row. Well I tried to replicate this:
$result_set = $database->query($sql);
while($row = mysqli_fetch_array($result_set)){
some code
}
with this:
$a = ["a","b","c"];
$num = 1;
while($row = $a){
echo $num;
$num++;
}
and I get an infinite loop. What am I missing?
In order to replicate the behavior of mysqli_fetch_array() with an array you create consider the following: first create an array of arrays:
$a = ["a"=>array(1,2,3),"b"=>array(4,5,6),"c"=>array(7,8,9)];
$num = 1;
One way (there is more than one way to skin this proverbial cat) is to use a foreach()loop to get and manipulate (echo) each row:
foreach($a AS $row){
echo $num ."\n";
$num++;
echo $row[0] . " " . $row[1] . " " .$row[2] . "\n";
}
This returns just what you would expect, your number followed by the data in each row of $a example:
1
1 2 3
2
4 5 6
3
7 8 9
Once the loop has reached the end of the array it will exit, same as mysqli_fetch_array() which essentially says, "foreach result_set as row".
You can try this with while loop which is like while($row = mysqli_fetch_array($result_set))
$a = ["a","b","c"];
$num = 0;
while($num < count($a)){
echo $a[$num]."\n";
$num++;
}
Related
This question already has answers here:
Selecting multiple array elements
(3 answers)
Closed 1 year ago.
Hey GUys Im beginner to php programming here here i have 15 element in array . i want to display first 4 array element in first line and then second 4 array of element in nextline . i dont know how to achive it here is my code help me on this. thanks in advance
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
echo $nr_elm = count($arry); // gets number of elements in $arry
$nr_col = 4; // Sets the number of text Per Line
// If the array has elements
if ($nr_elm > 0)
{
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++)
{
echo $textInLine= $arry[$i]. ' | ';
// If the number of columns is completed for a line (rest of division of ($i + 1) to $nr_col is 0)
// Closes the current line, and begins another line
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $textInLine .= '/n'; }
}
}
echo $textInLine;
?>
Use array_chunk for this:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
foreach (array_chunk($array, $size) as $chunk) {
echo implode(' ', $chunk) . PHP_EOL;
}
Another solution without using array_chunk is using modulo:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
$counter = 0;
foreach ($array as $character) {
echo $character;
// echo new line after every 4th character, a space after the others
echo (++$counter % $size === 0) ? PHP_EOL : ' ';
}
Chunk the array and implode the items in the chunk.
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$chunks = array_chunk($array, 4);
foreach($chunks as $chunk){
echo implode(" ", $chunk) . "</br>\n";
}
Array_chunk splits the array in to pieces of the size you define.
The resulting array is multidimensional with the items in the subarray.
Implode takes the items in the subarray and adds the delimiter (" ") in between each item and makes it a string.
Use array_chunk, it will Split an array into chunks
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$arr = array_chunk($arry, 4, true);
foreach($arr as $value) {
echo implode(' ', $value) . PHP_EOL ;
}
?>
I don't know if the "15" is intentional, but if you want to remove it just remove the "echo".
I also recommend to use empty() to verify if your array is empty or not, just like this :
if (!empty($arry)) { //Code }
(notice the "!")
Now, for your main question what I would do is using a variable which increments up to 4, then you insert a line break with echo <br>; and reset the variable to 0.
The code should look something like this :
$c = 0;
for($i=0; $i<$nr_elm; $i++)
{
echo $arry[$i];
$c ++;
if ($c >= 4) {
echo "<br>";
$c = 0;
}
}
I hope this helped you
I have a while loop that loops through line of text
while ($line_of_text = fgetcsv($file_processing, 4096)) {
In this while loop I assign variables to different parts of the array
IF($i > 0)
{
echo "</br>";
$account_type_id = $line_of_text[0];
echo "Account Type ID: " . $account_type_id. "<br>";
$account_number = $line_of_text[1];
echo "account_number = " . $account_number . "<br>";
This while loop loops through many lines. I am trying to find a way to say that
IF $account_type_id == 99 then add $account_number to an array. Then outside of the while loop print out the whole array of $account_numbers where $account_type_id == 99.
I have tried using print_r but it will only display the last array...
To add the element to an array, you can use array_push.
First you need to create the array (before the while loop):
$my_array = array();
Then, in the while loop, do this:
if ($account_type_id == 99) {
array_push($my_array, $account_number);
}
Then to display the array, either use print_ror var_dump. To make the array easier to read, you can also do this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Rocket H had the answer in the comment he posted
inside of your loop
if($account_type_id == 99){
$account_numbers[] = $account_number;
}
After loop
print_r($account_numbers);
I have a table that I need to find "top trusted builder" from, Trusts are separated by " ; ", So I need to pull all the data, explode the usernames, order and count them, and Im stuck on finally outputting the top username form the array, I have posted up the full segment of PHP, because im sure there has to be a much better way of doing this.
<?php
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);
$buildersarray = array();
while($row = $GTB->fetch()) {
$allbuilders = explode(";", $row['builders']);
for($i = 0; $i < count($allbuilders); $i++)
{
$buildersarray[] = $allbuilders[$i];
}
}
echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>
Outputs
Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)
You can return the array from the array_count_values command into a new array called $topbuilders, and then echo out the current (first) record:
$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);
current() will return the first item in an associative array.
Instead of using array_count_values() it would be better to use the names as the key to a frequency array:
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$result = array();
while (($builders = $GTB->fetchColumn()) !== false) {
foreach (explode(";", $builders) as $builder) {
if (isset($result[$builder])) {
$result[$builder]++;
} else {
$result[$builder] = 1;
}
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);
echo "Name = ", key($result), " Count = ", current($result), "\n";
I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.
This is driving me nuts! I need to fill up and HTML table with values that I pulled out from a DB.
The HTML table has 100 one td for each value.
I have an array that I populate doing this:
$x = 1;
$ArrayA = array();
for ($x = 1; $x <= 100; $x++) {
$ArrayA[$x] = 0;
}
So now I have an array with 100 values, right?
Then I query my DB, and get the result that I "want"
(select num from table1)
6 rows with the following values:
1,3,14,50,100.
Then I insert the values from my query into the $ArrayA that I populated before with one hundred 0's
$x = 1;
while ($row = mysql_fetch_array($result))
{
extract($row);
$ArrayA[$x] = "$num";
$x++;
}
Now $ArrayA has this:
1,3,14,17,100,0,0,0,0,0,0,0,0,0,0,0,0.....
And my goal is to replace with a 0 where I should have a "next" number, hard to explain..
I need this result:
1,0,3,0,0,0,0,0,0,0,0,0,0,14,0,0,17,0....
I tried to use PHP array_splice, but it did not work.
I tried with some if statements but my logic and programing experience is not that good.
Any suggestions?
Thanks
If i understand this right, you want to add a zero after every element returned by your query? Right? If so, why not add a zero right after you add an element into the array?
$x = 1; while ($row = mysql_fetch_array($result)) {
extract($row);
$ArrayA[$x] = "$num";
$x++;
$ArrayA[$x] = "0"; //adds zero after every $num insert
}
Maybe you can clarify if this isn't what you're asking...
$match_rows = mysql_fetch_array($result);
$rows = range(1,100);
foreach( $rows as $row){
echo '<td>';
if( in_array($row, $match_rows) ){
echo $row;
}else{
echo 0;
}
echo '</td>' . PHP_EOL;
}
Sorry, that is untested - it could be shorter or neater, but like that possibly illustrates another way of achieving what you want.
I think this is what you want for your second code block:
while ($row = mysql_fetch_array($result))
{
extract($row);
if($num > 0 && $ <= 100 )
{
$ArrayA[$num] = "$num";
}
}
If your DB values are 3, 10, 15, 22, 100, you'd end up with 0,0,3,0,0,0,0,0,0,10,0,0,0,0,15, etc etc.