It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have the following PHP code to display my tag cloud. It seems if I don't have at least two tags that are the same, I get a warning message saying Warnng: Division by zero (shown below).
Could some one please help me fix this code? Thank you!
<?php
// define variables
$fontSizeUnit = "px";
$maxFontSize = 40;
$minFontSize = 10;
$tagsToDisplay = 100;
$tagDivider = " ";
// font size range
$fontSizeSpread = $maxFontSize - $minFontSize;
// create blank arrays
$tagArray = array();
$tempTagArray = array();
// DB: get all public tags
$result = mysqli_query($conn, "SELECT Tags FROM blog WHERE Tags != '' AND IsPublic = 1 ORDER BY RAND()")
or die($dataaccess_error);
if(mysqli_num_rows($result) > 0 )
{
// loop through results
while($row = mysqli_fetch_array($result))
{
// split the results
$tempStringArray = preg_split("/,/", $row['Tags']);
// loop through all items of this string array
for ($a = 0; $a < count($tempStringArray); $a++)
{
// convert to lowercase
$tempStringArray[$a] = strtolower($tempStringArray[$a]);
// check if it exists in tag array
if (empty($tagArray[$tempStringArray[$a]]))
{
// if it doesn't exist, create it with value 1
$tagArray[$tempStringArray[$a]] = 1;
}
else
{
// if it does exist, increase the value by 1
$tagArray[$tempStringArray[$a]] += 1;
}
}
}
// store to temporary array and sort descending
arsort($tagArray);
$numberOfTags = 0;
foreach ($tagArray as $key => $val)
{
$numberOfTags++;
if ($numberOfTags > $tagsToDisplay)
{
break;
}
$finalTagArray[$key] = $val;
}
ksort($finalTagArray);
$maxTagCount = max($finalTagArray);
$minTagCount = min($finalTagArray);
$tagCountSpread = $maxTagCount - $minTagCount; // <<== Problem here...
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
// function to calculate the font size
function calcSize($thisTagCount) {
// import necessary global variables
global $minTagCount, $minFontSize, $fontSizeUnit, $unitsPerCount;
// calculate font size
$thisFontSize = $minFontSize+($unitsPerCount*($thisTagCount-$minTagCount));
// round font size and add units
$thisFontSize = round($thisFontSize) . $fontSizeUnit;
// return font size
return $thisFontSize;
}
// echo out the resulting tags
$b = 1;
foreach ($finalTagArray as $key => $val)
{
echo "<a href='snippets-by-tags.php?tag=".urlencode($key)."' style='font-size: ";
echo calcSize($val);
echo "'>" . htmlentities($key) . "</a>";
if($b != count($finalTagArray))
{
echo " " . $tagDivider . " ";
}
$b++;
}
}
else
{
echo 'none found ...';
}
?>
You should check if $tagCountSpread is 0, obviously dividing with 0 = infinite. (Hence you receive an error). This could be an quick fix, but you should really think of the proper solution for your application.
if ($tagCountSpread <= 0) $tagCountSpread = 1;
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
Your problem is actually with this line:
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
If $tagCountSpread is zero, this is a division by zero. That will happen when $maxTagCount and $minTagCount are the same.
You should guard against this:
if ($tagCountSpread != 0)
{
$unitsPerCount = $fontSizeSpread / $tagCountSpread;
}
else
{
// sensible recovery code
}
// ...
$minTagCount = min($finalTagArray);
if(($tagCountSpread = $maxTagCount - $minTagCount) === 0){
// do something else when its zero; throw an exception, throw a party... whatever
}
// otherwise continue
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
// ...
Perhaps your problem is the following line:
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
And not the previous one. You should check if $tagCountSpread is NULL (0) and if not, do the division:
if($tagCountSpread != 0)
{
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
}else{
///something
}
PHP will show what line it happens on, figure out why it's dividing by zero and fix that (Probably using some conditionals).
Related
This question already has answers here:
PHP Displaying a number of asterisks depending on the number given in the input field
(4 answers)
Closed 11 months ago.
Question :
My Code :
<html\>
Enter the number of rows:
<?php
if($_POST)
{
$row = $_POST['row'];
if(!is_numeric($row))
{
echo "Make sure you enter a NUMBER";
return;
}
else
{
for($row=0;$row<=1;$row++){
for($j=0;$j<=$row;$j++){ echo "#"; } echo ""; }}}?>
The problem is it's showing only two rows
I expected as shown in the photo
$row = 10;
for($i=0;$i<=$row;$i++){
for($j=0;$j<=$i;$j++){ echo "#"; } echo "<br>"; }
You are overriding the $row variable.
Also, you don't need the else since you are returning in case the if(!is_numeric) is true;
This should do it.
if(isset($_POST['row'])) {
$rows = $_POST['row'];
if(!is_numeric($rows))
{
echo "Make sure you enter a NUMBER";
return;
}
for($row=0;$row<=$rows;$row++){
for($j=0;$j<=$row;$j++){
echo "#";
}
echo "\n";
}
}
You can make use of the PHP function str_repeat to simplify the script.
This would only take 1 loop, so you don't get confused with the variable names.
$row = 10;
$i = 1;
while ($i <= $row)
{
echo str_repeat("#", $i); echo "\n";
$i ++;
}
Working Example here.
just developed a simple CLI php code that calculates the multiplication table of your choosen size but when I check the files to make sure they stick to PSR coding standards, it gives me four errors/violations. I don't know where in the files the errors are after several attempts and days of work on the files.
there are two files:
cliVersion.php and generateCLITable.php
The first file gives me 1 PSR error and the second one gives me 3 PSR errors.
this is how I generate the multiplication table of size 12 on command line :
php cliVersion.php 12
can anyone help me to find out the PSR errors in the files.
here's the files and the error report:
cliVersion.php
<?php
declare(strict_types=1);
require_once 'generateCLITable.php';
require_once '../model/validateInput.php';
?>
<?php
// Assign the user's input argument value to $input variable
$inputString = $argv[1];
$errorMessage = "Please enter a valid argument (a whole number greater than 1)";
// Check if the user's input argument is not null or empty
if ($inputString == null || $inputString == "") {
echo $errorMessage;
} else {
// Create an object of ValidateInput Class
$inputData = new ValidateInput();
/*
Validate the $input variable received from the user as an argument.
The code will be safe to be processed after this line.
*/
$validatedInput = $inputData->validateInputData($inputString);
$validatedInputInt = (int)$validatedInput;
/*
Check if the validated input is an Integer and if it is,
generates the table else returns the error message
*/
$isInputValidInt = $inputData->isInputInt($validatedInputInt);
if ($isInputValidInt && $validatedInputInt > 1) {
$multTable = new MultTable();
$multTable->generateTable($validatedInputInt);
} else {
echo $errorMessage;
}
}
echo PHP_EOL;
GenerateCLITable.php
<?php
declare(strict_types=1);
class MultTable
{
/**
* The public generateTable function generates the multiplication table
*
* #param int $inputValue
*
* #return void
*/
public function generateTable(int $inputValue)
{
// Create first row of table headers - green colour
for ($col=1; $col <= $inputValue; $col++) {
echo "\033[35m \t$col \033[0m";
}
// Create remaining rows
for ($row=1, $col=1; $row <= $inputValue; $row++) {
echo "\n";
// First cell is a table header - green colour
if ($col == 1) {
echo "\033[35m \n$row \033[0m";
}
while ($col <= $inputValue) {
echo "\t" . $row * $col++ ;
}
// Reset $col at the end of the row
$col = 1;
}
}
}
Error report:
cliVersion.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
generateCLITable.php
----------------------------------------------------------------------
FOUND 3 ERRORS AFFECTING 3 LINES
I strongly recommend to use https://github.com/FriendsOfPHP/PHP-CS-Fixer in such cases.
I guess you are trying to unit test the code. I would probably focus on trying to be as thoughtful with the code first . Take cliVersion, I think you can simplify it greatly by creating a single method to handle the input. Also I find a lot of issue with your comments and variables and overdesign.
Revised Version:
<?php
//declare(strict_types=1); // I'm using php 5 so I don't have this (but ok for you)
require_once 'generateCLITable.php';
require_once '../model/validateInput.php';
$must_be_gtr_than = 1; // set floor val for validation
$inputData = new ValidateInput($must_be_gtr_than);
$multTable = new MultTable();
if ($inputData->isValidIntegerData($argv[1])) {
$tableSize = (int) $argv[1];
$multTable->generateTable($tableSize);
} else {
echo "Error: Please enter a valid argument (a whole number greater than ".$must_be_gtr_than.")";
die();
}
In this example I have one method alone that validates that I have an integer > 0, if isValidIntegerData than proceed . Think about ease of code and names that make sense generateTable doesn't tell me much, is there a better name ? Things like that. Take "$validatedInputInt", that doesn't speak to what you are doing as well as what that int is, "tableSize" makes more sense to me. Also we many times save camel back for Classes etc.. I would look up PSR2.
For example we use
CONST_SOMETHING = xx; //constants
var_x or varx // lowercase for vars
methodX //camel back
ClassName // ucwords for classes
etc..
UPDATE:
This is how I would probably go about building something like this:
<?php
//declare(strict_types=1); // PHP5.x Example
class GenerateCLITable
{
const DEFAULT_BOARD_SIZE = 12;
public $game_board, $table_size;
public function __construct($input = self::DEFAULT_BOARD_SIZE)
{
$this->game_board = $this->generateTable($input);
}
public function generateTable($inputValue = self::DEFAULT_BOARD_SIZE)
{
$table = "";
// Create first row of table headers - green colour
for ($col=1; $col <= $inputValue; $col++) {
$table .= "\033[35m \t$col \033[0m";
}
// Create remaining rows
for ($row=1, $col=1; $row <= $inputValue; $row++) {
$table .= "\n";
// First cell is a table header - green colour
if ($col == 1) {
$table .= "\033[35m \n$row \033[0m";
}
while ($col <= $inputValue) {
$table .= "\t" . $row * $col++ ;
}
// Reset $col at the end of the row
$col = 1;
}
$this->game_board = $table;
$this->table_size = $inputValue;
return $table;
}
public function isValidInputValue($input = '', $size = 0)
{
return (!empty($input) && $input > $size) ? (is_int((int) $input)) : false;
}
}
//require_once 'generateCLITable.php';
$multTable = new GenerateCLITable();
$must_be_gtr_than = 1;
if (!$multTable->isValidInputValue($argv[1], $must_be_gtr_than)) {
echo "Error: Please enter a valid argument (a whole number greater than ".$must_be_gtr_than.")";
die();
}
$table = $multTable->generateTable((int) $argv[1]);
echo $table . "\n";
Suppose I have an array with ie. $user_all_activity in code, i must check 5 activity in 10 minute(which is done by getDifference(),which return true is condition matches).If condition matched the condition,now i must check 5 activity in 10 minute after the condition matched.And this will be repeated several times.I put some late night programming here.
//$$user_all_activity take all activity of user A
if(!$user_all_activity == NULL)
{
$size = sizeof($user_all_activity);
//$prev_array = array();
for( $i=0; $i<$size-1;$i++)
{
if($i>3)
{
$prev_array = $user_all_activity[$i-4];
$current_array = $user_all_activity[$i];
//get difference check for difference 10
if($this->getDifference($current_array,$prev_array))
{
echo "Table update at id ".$current_array['id']." </br>";
}
}
}
}
The problem for me when condition matched.I must check again the same thing.May be good to use recursive.Sorry for not explaining the problem before.Hope you get the question.Thanks
Set a variable, and then check it later.
if($user_all_activity != NULL)
{
$size = sizeof($user_all_activity);
$difference_found = false;
for( $i=0; $i<$size-1;$i++)
{
if($i>3)
{
$prev_array = $user_all_activity[$i-4];
$current_array = $user_all_activity[$i];
//get difference check for difference 10
if($this->getDifference($current_array,$prev_array))
{
echo "Table update at id ".$current_array['id']." </br>";
$difference_found = true;
}
if ($difference_found) {
// do something
}
}
}
}
I have a function that will take an id and with that find out other information in the database relating to it spread among 3 tables. It then compares this to a csv file which at most times is cpu intensive. Running this once with one id takes approx 8 to 10 sec at most but I have been asked to have it run automatically across a varing number of ids in the database. To do this I created an array of the ids that match the criteria in the database at any point and then run a 'while' statement to repeat the function for each element in the array but it gets as far as maybe 4 of them and I get the following error:
Server error!
The server encountered an internal error and was unable to complete
your request. Either the server is overloaded or there was an error in
a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
I'll admit that my code could be much much cleaner as I'm still learning as I go but the real bottle neck appears to be reading the csv which is a report which size changes each day. I have tried different combinations and the best result is (please don't chastise me for this as I know it is stupid but the other ways haven't works as of yet) to run the code as follows:
$eventArray = eventArray($venueId);
$totalEvents = count($eventArray);
for($i=0; $i<$totalEvents; $i++)
{
$eventId = $eventArray[$i];
echo $eventId;
echo $datename = getEventDetails($eventId, $zone);
// date of event
echo $eventDate = $datename['eventDate'];
// vs team
echo $eventName = $datename['eventName'];
$file_handle = fopen("data/rohm/sales/today.csv", "r");
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 200);
include('finance_logic.php');
}
fclose($file_handle);
}
Yes, it is repeating the reading of the csv every time but I couldn't get it to function at all any other way so if this is the issue I would really appreciate some guidence on dealing with the csv better. Incase it is relevent the code it 'finance_logic.php' is listed below:
if($line_of_text[0] == "Event: $eventName ")
{
$f = 1;
$ticketTotalSet = "no";
$killSet = 'no';
// default totals zero
$totalHolds = 0;
$totalKills = 0;
$ticketSold = 0;
$ticketPrice = 0;
$totalCap = 0;
}
if($f == 1 && $line_of_text[0] == "$eventDate")
{
$f = 2;
}
if($f == 2 && $line_of_text[0] == "Holds")
{
$f = 3;
while($line_of_text[$col] !== "Face Value Amt")
{
$col++;
}
}
if($f == 3 && $line_of_text[0] !== "Face Value Amt")
{
if($f == 3 && $line_of_text[0] == "*: Kill")
{
$totalKills = $line_of_text[$col];
}
$holdsArray[] = $line_of_text[$col];
}
if($f == 3 && $line_of_text[0] == "--")
{
$f = 4;
}
if($f == 4 && $line_of_text[0] == "Capacity")
{
$totalCap = $line_of_text[$col];
$f = 5;
}
if($f == 5 && $line_of_text[0] == "Abbreviated Performance Totals")
{
$f = 6;
}
if($f == 6 && $line_of_text[0] == "$eventName")
{
// change when 1 ticket exists
$ticketTotalSet = "yes";
// set season tickets
include("financial/seasontickets/$orgShortName.php");
// all non season are single tickets
if(!isset($category))
{
$category = 'single';
}
$ticketName = $line_of_text[2];
$ticketSold = $line_of_text[3];
$ticketPrice = $line_of_text[4];
addTicketType($eventId, $ticketName, $category, $ticketSold, $ticketPrice);
unset($category);
}
if($f == 6 && $ticketTotalSet == "yes" && $line_of_text[0] !== "$eventName")
{
$totalHolds = (array_sum($holdsArray) - $totalKills);
// add cap, holds and kills
addKillsHoldsCap($eventId, $totalCap, $eventId, $totalHolds, $totalKills);
// reset everything
$f = 0;
$ticketTotalSet = "no";
echo "$eventName updated!";
}
Thanks in advance!
p.s. The reason the report is called each time is so that the 'eventName' and 'eventDate' are searched for with the 'finance_logic.php'. Obviously if this was set with all event names and dates already it would take one search of the report to find them all but I'm not sure how I could do this dynamically. Any suggestions would be welcome as I'm sure there is something out there that I just haven't learnt yet.
I have some heavy script i use with localhost sometimes and if i don't add anything they will just time out.
A simple solution is to limit the number of execution of your function, then reload the page, then restart where you stopped.
I don't know if I have suffered some brain or sight damage, but I can't understand behavior of this code:
$po=1;
$po2=0;
echo $po.'*'.$po2.'=';
if($po*$po2) $po=1;
echo $po;
I'd expect the output to be 1*0=0, but actually it's 1*0=1.
$po is always 1. You initialize it to 1, and later in your if case, you have no else. So it remains 1.
Instead, add an `else:
$po = 1;
$po2 = 0;
echo $po.'*'.$po2.'=';
if ($po * $po2) {
// Unnecessary - it's already 1
$po = 1;
}
// Set it to 0...
else {
$po = 0;
}
echo $po;