Good day, I was tasked to make a variable counter in php.
Im stuck at the last stage. And that is to display the total number of positive values. I used the count() in php, but it's not giving me the total number. is there a way that i can get the summation of the value that is is count()?
if ($start < $end)
{
for($ctr = $start; $ctr<=$end; $ctr++)
{
if ($ctr == 0)
{
echo " <br/ >there is a zero <br/ >";
}
else if ($ctr <=0)
{
echo count($ctr) . " negative value" ;
}
else if($ctr >=0)
{
echo count($ctr) . " positive value ";
}
}
$zero = $pos = $neg = 0;
for($ctr = $start; $ctr<=$end; $ctr++)
{
switch(true){
case $ctr==0: $zero++; break;
case $ctr<0: $neg++; break;
case $ctr>0: $pos++; break;
}
}
if($zero)
echo "there is a zero<br/>";
if($pos)
echo "$pos positive values<br/>" ;
if($neg)
echo "$neg negative values<br/>" ;
Better way is without any loop:
function test($start, $end) {
echo "Test of [$start, $end]:\n";
if ($isThereZero = $start * $end <= 0) {
echo "There is zero\n";
}
if ($start < 0) {
$negatives = $isThereZero ? -$start : -$start+$end;
echo "$negatives negative values\n";
}
if ($end > 0) {
$positives = $isThereZero ? $end : $end - $start;
echo ($positives)." positive values\n";
}
}
test(-12, 5);
test(-12, -5);
test(5, 12);
test(0, 0);
Try that :
$zer = 0;
$pos = 0;
$neg = 0;
if ($start < $end)
{
for($ctr = $start; $ctr<=$end; $ctr++)
{
if ($ctr == 0)
{
$zer++;
}
else if ($ctr < 0)
{
$neg++;
}
else if($ctr > 0)
{
$pos++;
}
}
echo $zer . " zero value" ;
echo $neg . " negative value" ;
echo $pos . " positive value ";
Just for fun, this could be done without a loop. This is a bit tricky and also a bit far from the initial question :
Demo
$start = -3;
$end = 5;
echo ($start <= 0 && $end >= 0 ? "1" : "0")." zero value\n";
echo ($start < 0 && $start <= $end ? (-$start-($end > -1 ? 0 : -$end-1)) : "0"). " negative value\n";
echo ($end > 0 && $start <= $end ? ($end-($start < 1 ? 0 : $start-1)) : "0"). " positive value\n";
else if($ctr >=0)
{
$cnt++; //or $cnt+=1;
}
Then use $cnt++ for no of count for positive vales
Related
Someone please help me to create a two triangle patter using PHP. I'm already code but the output didn't as expected below.
expected output
My code:
function generatePattern($num) {
for ($id1 = 0; $id1 <= $num; $id1 = $id1 + 1) {
for ($id2 = $num; $id2 >= $id1; $id2 = $id2 - 1) {
print(' ');
}
for ($id3 = 1; $id3 <= $id1; $id3 = $id3 + 1) {
if ($id3 % 4 == 3) {
echo "o";
} else if ($id3 % 2 == 1) {
echo "x";
} else {
echo " ";
}
}
echo "\n";
}
for ($id1 = 0; $id1 <= $num-1; $id1 = $id1 + 1) {
echo str_repeat(' ', $num - 1);
for($id3 = $num-1; $id3 >= $id1; $id3 = $id3 - 1){
if ($id3 % 4 == 3) {
echo "o";
} else if ($id3 % 2 == 1) {
if ($id1 % 4 == 3) {
echo "o";
} else if ($id1 % 2 == 0) {
echo " ";
} else if ($id1 % 2 == 1) {
echo "x";
} else {
echo "x";
}
} else if ($id3 == $id1){
echo "x";
} else {
echo " ";
}
}
echo "\n";
}
}
generatePattern(4);
And my current output like this (the bottom triangle still messed up)
output
Do the required changes for space between o and x
function generatePattern($num) {
if($num % 2 == 0)
{
$num1 = $num + 1;
}else{
$num1 = $num;
$num = $num - 1;
}
for ($id1 = 1; $id1 <= $num; $id1++) {
for ($id2 = $num; $id2 >= $id1; $id2--) {
print(' ');
}
for ($id3 = 1; $id3 <= $id1; $id3++) {
if ($id3 % 4 == 3) {
echo "o";
} else if ($id3 % 2 == 1) {
echo "x";
} else {
echo " ";
}
}
echo "\n";
}
$str = str_repeat('x o ', ceil(($num1*2)/4));
echo substr($str, 0, $num1*2);
echo "\n";
$j = $num;
for($id1 = $num; $id1 >=1; $id1 = $id1 - 2)
{
for($id2 = 2; $id2 >= 1; $id2--)
{
if($j % 2 == 0)
{
$pattern = [' ', 'x', ' ', 'o',];
}else{
$pattern = [' ', 'o', ' ', 'x',];
}
echo str_repeat(' ', ($id2%2 == 0) ? $num: $num - 1);
$design = implode('', $pattern);
do{
$design .= implode('', $pattern);
}while(strlen($design) < $id1);
echo substr($design, 0, $id1);
echo "\n";
}
$j--;
}
}
generatePattern(14);
I have created the following script for determining which page numbers to display for navigation on my website.
// query the database
$statement = $connect->prepare("SELECT COUNT(report_number) FROM reports");
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
$rowCount = $result["COUNT(report_number)"];
$pgCount = ceil($rowCount / 10);
// fetch the corresponding entries from the database
if (!isset($pgParamArray["page"]) || $pgParamArray["page"] === $pgCount) {
$pgParamArray["page"] = $pgCount;
$sql = "SELECT * FROM reports ORDER BY report_number DESC LIMIT 10";
} elseif (isset($pgParamArray["page"])) {
$offset = ($pgCount - $pgParamArray["page"]) * 10;
$sql = "SELECT * FROM reports ORDER BY report_number DESC LIMIT " . $offset . ",10";
}
// calculate and display the appropriate page numbers
$upperDiff = $pgCount - $pgParamArray["page"];
$lowerDiff = $pgParamArray["page"] - 1;
for ($i = 0; $i < 5; $i++) {
$pgNo = 0;
if ($pgParamArray["page"]+2 <= $pgCount && $pgParamArray["page"]-2 >= 1) {
$pgNo = $pgParamArray["page"] + ($i - 2);
} elseif ($pgCount < 5) {
$pgNo = $i+1 <= $pgCount ? $i+1 : 0;
} elseif ($upperDiff < $lowerDiff && $upperDiff < 2 && $upperDiff >= 0) {
$pgNo = ($pgCount - 4) + $i;
} elseif ($lowerDiff < $upperDiff && $lowerDiff < 2 && $lowerDiff >= 0) {
$pgNo = $i + 1;
} else {
$pgNo = ($pgCount - 4) + $i;
}
if ($pgNo > 0) {
if ($pgNo !== $pgParamArray["page"]) {
$pgNoArray[] = ""
. "<li><div><a href='http://www.somewebsite.com/index.php/?page="
. $pgNo
. "'>"
. $pgNo
. "</a></div></li>";
} else {
$pgNoArray[] = ""
. "<li><div style='background:#333'>"
. $pgNo
. "</div></li>";
}
}
}
When I set $pgParamArray["page"] = $pgCount = ceil($rowCount/10), I have noticed that the foremost variable is still treated as a float. My question is why is $pgParamArray["page"] of type float even though ceil($rowCount/10) obviously returns an integer?
PHP's ceil returns a float according to their documentation.
Their rationale:
value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.
This isn't just PHP that does this - C++ and Java both return floating point values for their ceiling functions.
I'm having trouble making a simple count work. Right now 0 is constantly displayed when I run the code and I know it's because I set count to 0. But it should be displaying the number of times "Fizz" is displayed.
I'm sure it's simple but I just can't see what!
public function __construct($firstParam, $secondParam, $firstSound = "Fizz", $secondSound = "Buzz", $numbers = 100) {
$this->firstParam = $firstParam;
$this->secondParam = $secondParam;
$this->firstSound = $firstSound;
$this->secondSound = $secondSound;
$this->numbers = $numbers;
$this->numsArray = $numsArray;
}
public function __toString() {
$count = 0;
for ($i = 0; $i < count($this->numsArray); $i++){
$val = $this->numsArray[$i];
if ($val == $this->firstSound) {
$count++;
}
}
$print = "Number of Fizzes: ".$count;
return $print;
}
public function execute() {
$this->numsArray = array();
if ($this->secondParam > $this->firstParam) {
for ($i = 1; $i <= $this->numbers; $i++){
if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) {
$this->numsArray[] = "\n".$this->firstSound.$this->secondSound."\n";
} elseif ($i % $this->firstParam == 0) {
$this->numsArray[] = "\n".$this->firstSound."\n";
} elseif ($i % $this->secondParam == 0) {
$this->numsArray[] = "\n".$this->secondSound."\n";
} else {
$this->numsArray[] = "\n".$i."\n";
}
echo $this->numsArray[$i-1];
}
} else {
echo "\n".' First Number Bigger Than Second '."\n";
}
}
In your execute you are not assigning the values to numsArray[i] also you inject new line characters that will not match the equality you just when checking $val. Also I notice you use zero index to check them and index 1 to load it. Change execute to:
for ($i = 0; $i < $this->numbers; $i++){
if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) {
$this->numsArray[i] = $this->firstSound.$this->secondSound;
} elseif ($i % $this->firstParam == 0) {
$this->numsArray[i] = $this->firstSound;
} elseif ($i % $this->secondParam == 0) {
$this->numsArray[i] = $this->secondSound;
} else {
$this->numsArray[i] = $i;
}
echo $this->numsArray[$i];
This is a better binary string comparison for php...
if (strcmp($val, $this->firstSound) == 0)
This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 7 years ago.
I have the below function, But when I run the code make error like:
Fatal error: Using $this when not in object context in E:....
How to fix it. I replace $this-> with self:: but it failed too.
Please help in this regards,
<?php
function cehck_files()
{
$file1 = 'C:\xampp\htdocs\test\test1.php';
$file2 = 'C:\xampp\htdocs\test\test2.php';
$test = $this->compareFiles($file1,$file2,true);
$test_display = $this->toTable($test);
echo "<pre>";
print_r($test_display);
print_r($test);
echo "</pre>";
}
function compareFiles($file1, $file2, $compareCharacters = false) {
return $this->compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
}
function compare($string1, $string2, $compareCharacters = false) {
$start = 0;
if ($compareCharacters){
$sequence1 = $string1;
$sequence2 = $string2;
$end1 = strlen($string1) - 1;
$end2 = strlen($string2) - 1;
} else {
$sequence1 = preg_split('/\R/', $string1);
$sequence2 = preg_split('/\R/', $string2);
$end1 = count($sequence1) - 1;
$end2 = count($sequence2) - 1;
}
// skip any common prefix
while ($start <= $end1 && $start <= $end2 && $sequence1[$start] == $sequence2[$start]) {
$start ++;
}
// skip any common suffix
while ($end1 >= $start && $end2 >= $start && $sequence1[$end1] == $sequence2[$end2]) {
$end1 --;
$end2 --;
}
// compute the table of longest common subsequence lengths
$table = self::computeTable($sequence1, $sequence2, $start, $end1, $end2);
// generate the partial diff
$partialDiff =
self::generatePartialDiff($table, $sequence1, $sequence2, $start);
// generate the full diff
$diff = array();
for ($index = 0; $index < $start; $index ++){
$diff[] = array($sequence1[$index], UNMODIFIED);
}
while (count($partialDiff) > 0) $diff[] = array_pop($partialDiff);
for ($index = $end1 + 1; $index < ($compareCharacters ? strlen($sequence1) : count($sequence1)); $index ++) {
$diff[] = array($sequence1[$index], UNMODIFIED);
}
// return the diff
return $diff;
}
function computeTable($sequence1, $sequence2, $start, $end1, $end2) {
$length1 = $end1 - $start + 1;
$length2 = $end2 - $start + 1;
// initialise the table
$table = array(array_fill(0, $length2 + 1, 0));
// loop over the rows
for ($index1 = 1; $index1 <= $length1; $index1 ++) {
// create the new row
$table[$index1] = array(0);
// loop over the columns
for ($index2 = 1; $index2 <= $length2; $index2 ++){
// store the longest common subsequence length
if ($sequence1[$index1 + $start - 1] == $sequence2[$index2 + $start - 1]) {
$table[$index1][$index2] = $table[$index1 - 1][$index2 - 1] + 1;
} else {
$table[$index1][$index2] =
max($table[$index1 - 1][$index2], $table[$index1][$index2 - 1]);
}
}
}
// return the table
return $table;
}
function generatePartialDiff( $table, $sequence1, $sequence2, $start ) {
$diff = array();
// initialise the indices
$index1 = count($table) - 1;
$index2 = count($table[0]) - 1;
// loop until there are no items remaining in either sequence
while ($index1 > 0 || $index2 > 0){
// check what has happened to the items at these indices
if ($index1 > 0 && $index2 > 0 && $sequence1[$index1 + $start - 1] == $sequence2[$index2 + $start - 1]) {
// update the diff and the indices
$diff[] = array($sequence1[$index1 + $start - 1], UNMODIFIED);
$index1 --;
$index2 --;
} elseif ($index2 > 0 && $table[$index1][$index2] == $table[$index1][$index2 - 1]) {
// update the diff and the indices
$diff[] = array($sequence2[$index2 + $start - 1], INSERTED);
$index2 --;
}else{
// update the diff and the indices
$diff[] = array($sequence1[$index1 + $start - 1], DELETED);
$index1 --;
}
}
// return the diff
return $diff;
}
function toTable($diff, $indentation = '', $separator = '<br>') {
$html = $indentation . "<table class=\"diff\">\n";
// loop over the lines in the diff
$index = 0;
while ($index < count($diff)){
// determine the line type
switch ($diff[$index][1]){
// display the content on the left and right
case UNMODIFIED:
$leftCell =
self::getCellContent(
$diff, $indentation, $separator, $index, UNMODIFIED);
$rightCell = $leftCell;
break;
// display the deleted on the left and inserted content on the right
case DELETED:
$leftCell =
self::getCellContent(
$diff, $indentation, $separator, $index, DELETED);
$rightCell =
self::getCellContent(
$diff, $indentation, $separator, $index, INSERTED);
break;
// display the inserted content on the right
case INSERTED:
$leftCell = '';
$rightCell =
self::getCellContent(
$diff, $indentation, $separator, $index, INSERTED);
break;
}
// extend the HTML with the new row
$html .=
$indentation
. " <tr>\n"
. $indentation
. ' <td class="diff'
. ($leftCell == $rightCell
? 'Unmodified'
: ($leftCell == '' ? 'Blank' : 'Deleted'))
. '">'
. $leftCell
. "</td>\n"
. $indentation
. ' <td class="diff'
. ($leftCell == $rightCell
? 'Unmodified'
: ($rightCell == '' ? 'Blank' : 'Inserted'))
. '">'
. $rightCell
. "</td>\n"
. $indentation
. " </tr>\n";
}
// return the HTML
return $html . $indentation . "</table>\n";
}
?>
You are using $this for a function which is not a method of any class.
Instead of
$test = $this->compareFiles($file1,$file2,true);
Use:
$test = compareFiles($file1,$file2,true);
Also, change
return $this->compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
To
return compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
And to the remaining changes in this way.
Currently, I'm learning to use Google Maps API. From what I read, the API require the latitude and longitude in Decimal Degree (DD).
In my database, the data is stored as DMS.
Example, 110° 29' 01.1"
I would to ask if you guys have any DMS to DD in php. And, the converter must accept from a single string like the example above.
Regards
You can try if this is working for you.
<?php
function DMStoDD($deg,$min,$sec)
{
// Converting DMS ( Degrees / minutes / seconds ) to decimal format
return $deg+((($min*60)+($sec))/3600);
}
function DDtoDMS($dec)
{
// Converts decimal format to DMS ( Degrees / minutes / seconds )
$vars = explode(".",$dec);
$deg = $vars[0];
$tempma = "0.".$vars[1];
$tempma = $tempma * 3600;
$min = floor($tempma / 60);
$sec = $tempma - ($min*60);
return array("deg"=>$deg,"min"=>$min,"sec"=>$sec);
}
?>
Here's one where you pass in the latitude,longitude in DMS values and returns the converted DMS string. Easy and simnple
function DECtoDMS($latitude, $longitude)
{
$latitudeDirection = $latitude < 0 ? 'S': 'N';
$longitudeDirection = $longitude < 0 ? 'W': 'E';
$latitudeNotation = $latitude < 0 ? '-': '';
$longitudeNotation = $longitude < 0 ? '-': '';
$latitudeInDegrees = floor(abs($latitude));
$longitudeInDegrees = floor(abs($longitude));
$latitudeDecimal = abs($latitude)-$latitudeInDegrees;
$longitudeDecimal = abs($longitude)-$longitudeInDegrees;
$_precision = 3;
$latitudeMinutes = round($latitudeDecimal*60,$_precision);
$longitudeMinutes = round($longitudeDecimal*60,$_precision);
return sprintf('%s%s° %s %s %s%s° %s %s',
$latitudeNotation,
$latitudeInDegrees,
$latitudeMinutes,
$latitudeDirection,
$longitudeNotation,
$longitudeInDegrees,
$longitudeMinutes,
$longitudeDirection
);
}
I wrote a PHP function that does what the question asks: converts a string in degrees/minutes/seconds into decimal degrees. It accepts a number of different formats for the string, and honors direction (NSEW).
Here is the code:
<?php
function convertDMSToDecimal($latlng) {
$valid = false;
$decimal_degrees = 0;
$degrees = 0; $minutes = 0; $seconds = 0; $direction = 1;
// Determine if there are extra periods in the input string
$num_periods = substr_count($latlng, '.');
if ($num_periods > 1) {
$temp = preg_replace('/\./', ' ', $latlng, $num_periods - 1); // replace all but last period with delimiter
$temp = trim(preg_replace('/[a-zA-Z]/','',$temp)); // when counting chunks we only want numbers
$chunk_count = count(explode(" ",$temp));
if ($chunk_count > 2) {
$latlng = $temp; // remove last period
} else {
$latlng = str_replace("."," ",$latlng); // remove all periods, not enough chunks left by keeping last one
}
}
// Remove unneeded characters
$latlng = trim($latlng);
$latlng = str_replace("º","",$latlng);
$latlng = str_replace("'","",$latlng);
$latlng = str_replace("\"","",$latlng);
$latlng = substr($latlng,0,1) . str_replace('-', ' ', substr($latlng,1)); // remove all but first dash
if ($latlng != "") {
// DMS with the direction at the start of the string
if (preg_match("/^([nsewNSEW]?)\s*(\d{1,3})\s+(\d{1,3})\s+(\d+\.?\d*)$/",$latlng,$matches)) {
$valid = true;
$degrees = intval($matches[2]);
$minutes = intval($matches[3]);
$seconds = floatval($matches[4]);
if (strtoupper($matches[1]) == "S" || strtoupper($matches[1]) == "W")
$direction = -1;
}
// DMS with the direction at the end of the string
if (preg_match("/^(-?\d{1,3})\s+(\d{1,3})\s+(\d+(?:\.\d+)?)\s*([nsewNSEW]?)$/",$latlng,$matches)) {
$valid = true;
$degrees = intval($matches[1]);
$minutes = intval($matches[2]);
$seconds = floatval($matches[3]);
if (strtoupper($matches[4]) == "S" || strtoupper($matches[4]) == "W" || $degrees < 0) {
$direction = -1;
$degrees = abs($degrees);
}
}
if ($valid) {
// A match was found, do the calculation
$decimal_degrees = ($degrees + ($minutes / 60) + ($seconds / 3600)) * $direction;
} else {
// Decimal degrees with a direction at the start of the string
if (preg_match("/^(-?\d+(?:\.\d+)?)\s*([nsewNSEW]?)$/",$latlng,$matches)) {
$valid = true;
if (strtoupper($matches[2]) == "S" || strtoupper($matches[2]) == "W" || $degrees < 0) {
$direction = -1;
$degrees = abs($degrees);
}
$decimal_degrees = $matches[1] * $direction;
}
// Decimal degrees with a direction at the end of the string
if (preg_match("/^([nsewNSEW]?)\s*(\d+(?:\.\d+)?)$/",$latlng,$matches)) {
$valid = true;
if (strtoupper($matches[1]) == "S" || strtoupper($matches[1]) == "W")
$direction = -1;
$decimal_degrees = $matches[2] * $direction;
}
}
}
if ($valid) {
return $decimal_degrees;
} else {
return false;
}
}
?>
Here it is on Github with test cases: https://github.com/prairiewest/PHPconvertDMSToDecimal
Solved.
<?php
function DMStoDD($input)
{
$deg = " " ;
$min = " " ;
$sec = " " ;
$inputM = " " ;
print "<br> Input is ".$input." <br>";
for ($i=0; $i < strlen($input); $i++)
{
$tempD = $input[$i];
//print "<br> TempD [$i] is : $tempD";
if ($tempD == iconv("UTF-8", "ISO-8859-1//TRANSLIT", '°') )
{
$newI = $i + 1 ;
//print "<br> newI is : $newI";
$inputM = substr($input, $newI, -1) ;
break;
}//close if degree
$deg .= $tempD ;
}//close for degree
//print "InputM is ".$inputM." <br>";
for ($j=0; $j < strlen($inputM); $j++)
{
$tempM = $inputM[$j];
//print "<br> TempM [$j] is : $tempM";
if ($tempM == "'")
{
$newI = $j + 1 ;
//print "<br> newI is : $newI";
$sec = substr($inputM, $newI, -1) ;
break;
}//close if minute
$min .= $tempM ;
}//close for min
$result = $deg+( (( $min*60)+($sec) ) /3600 );
print "<br> Degree is ". $deg*1 ;
print "<br> Minutes is ". $min ;
print "<br> Seconds is ". $sec ;
print "<br> Result is ". $result ;
return $deg + ($min / 60) + ($sec / 3600);
}
?>
If you also want to include the reference, you might want to use this function:
function DMStoDD($ref, $deg, $min, $sec)
{
$n = $deg + (($min * 60 + $sec) / 3600);
if (($ref == "S") or ($ref == "W")) {
return -$n;
} else {
return $n;
}
}
This works very well:
<?php echo "<td> $deg° $min' $sec″ </td>"; ?>
where deg, min and sec are the angular co-ordinates.