Convert PHP Array to Integer? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Convert PHP Array to Integer?

Hi I was fiddling around with MySQL and PHP and I was getting an issue with arrays, this question doesn't require SQL knowledge, just stick with me for a moment. Here's the source code: ~ SQL Code you don't care about ~ $query_retrieve_max = some command that will retrieve the max index of my database; $query_retrieve_max_result = mysqli_query($con, $query_retrieve_max); <-- also uninteresting $max_id=mysqli_fetch_assoc($query_retrieve_max_result); <--- the database gets the maximum index (in my case 3) and saves it to the variable "max_id". printf_r($max_id); results into this: "Array ( [total] => 3 )" The issue is I can't use that variable for a for-loop for example (amazing, 3 for's in one sentence). The site loads infinitely and in my case runs the for loop endlessly (creates infinite divs). How can I convert that "Array" Value to an integer type so its usable with for-loops and stuff?

9th Dec 2019, 6:51 PM
Wheres8
Wheres8 - avatar
1 Answer
0
How do you loop through all values of an array in PHP even when the keys are strings like 'total' instead of 0, 1, 2, 3, 4...? Answer: Use foreach. foreach is better for iterating through values of an array even if keys from 0, 1, 2, 3, 4, 5, ... are set. This is why foreach is more frequently used than for in PHP. foreach ($max_id as $val) { echo $val . ', '; } This would print '3, ' for you if $max_id is ['total' => 3] like you mentioned in the question. If you know that you just want the single value of the total, you can do $max_id['total']. If $max_id is ['total' => 3], $max_id['total'] is 3. You might want to learn more about PHP's arrays at: https://www.php.net/manual/en/language.types.array.php
11th Dec 2019, 6:46 PM
Josh Greig
Josh Greig - avatar