I'm trying to repeat the function only if the value is ",":
This is my code for trying to get the coordinates from an address but somtimes it gets only "," so I want it to try 10 times until it gets the full coordinates.
$coordinates1 = getCoordinates($placeadress);
$i == 0;
while (($coordinates1 == ',') && ($i <= 10)) {
$coordinates1 = getCoordinates($placeadress);
$i++;
}
The function code is this:
function getCoordinates($address) {
$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern
$address = str_replace("-", "+", $address); // replace all the "-" with "+" sign to match with google search pattern
$url = "http://maps.google.com/maps/api/geocode/json?address=$address";
$response = file_get_contents($url);
$json = json_decode($response,TRUE); //generate array object from the response from the web
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
}
May be try this
$coordinates1 = getCoordinates($placeadress);
$i = 0;
while ($i <= 10) {
$coordinates1 = getCoordinates($placeadress);
if($coordinates1==',')
$i++;
else
break;
}
It will break the loop as soon as co-ordinates value is not a comma and you are good to go. If it is a comma it will go for next iteration in while
You could just reduce all that code to a while with an empty block:
<?php
$i = 0;
while (
($coords = getLatLong($place))
&& $coords == ','
&& $i++ < 10
);
There's still perhaps no guarantee of the 'right' value being returned even after calling the function 10 times.
Related
Take an input string (via form post) which can contain single-digit numbers, letters, and question marks, and check if there are exactly 2 question marks between every pair of two numbers that add up to 12.
If so, return "Yes", otherwise it should return "No". If there aren't any two numbers that add up to 12 in the string, return "No".
For example: if str is "arrb7??5xxbl8??eee4" then your program should return true because there are exactly 2 question marks between 7 and 5, and 2 question marks between 8 and 4 at the end of the string.
enter code here
<?php
$value = $_POST['temp'];
$len = strlen($value);
// $splt = explode(",",$value);
// var_dump($splt);
// foreach($splt as $result)
// {
// echo $result ."<br>";
// }
$i=0;
strpos($value[i]);
if(is_numeric($value)&& $len < 12)
{
echo $value;
}
else
{
echo 'no';
}
// $temp = explode($value);
// if($value == )
// is_numeric($value);
enter code here
From your comments in your code, I understand you are trying to explode ','. That doesn't relate to any part of the logic. You might need to explode to split your string based on "??". To extract those pair of numbers before adding them, there are pre-defined methods like preg_match_all(). filter_var(), so on. Here's an example working:
<?php
$string = 'arrb7??5xxbl8??eee4';
$terms = explode("??",$string);
$success = true;
for ($counter=1; $counter < count($terms); $counter+=1) {
$num1 = ((int) filter_var($terms[$counter-1], FILTER_SANITIZE_NUMBER_INT)) % 10;
$num2 = ((int) filter_var($terms[$counter], FILTER_SANITIZE_NUMBER_INT));
$sum = $num1+((string)($num2))[0];
if ($sum != 12)
{
$success = false;
break;
}
}
echo $success ? "Yes" : "No";
?>
I have a FOR loop and an IF statement that checks each line for a certain word in a txt document. However when the loop gets to a line that holds the value 'header' the IF statement does not think it is true.
txt file
header
bods
#4f4f4f
30
100
1
text
this is content for the page
#efefef
10
300
2
img
file/here/image.png
300
500
filler
3
header
this is header text
#4f4f4f
30
100
4
php file
$order = array();
$e = 0;
$h = 0;
$headerCount = 0;
$textCount = 0;
$imgCount = 0;
//Open file putting each line into an array
$textFile = fopen("test.txt","r+");
$inTextFile = fread($textFile, filesize("test.txt"));
$arrayFile = explode("\n", $inTextFile);
$arrayFileSize = sizeof($arrayFile);
$elementCount = $arrayFileSize / 6;
for ($x = 0; $x < $arrayFileSize; $x++) {
if ($arrayFile[$x] == "header") {
echo $x;
echo " Yes : ".$arrayFile[$x] . "<br>";
$headerCount++;
}
else {
echo $x;
echo " No : " . $arrayFile[$x] . "<br>";
}
}
Welcome to Stack Overflow Billy. There are two solutions you can try: using the trim() function of strpos().
Using trim() will remove any leading or trailing spaces from a string:
if (trim($arrayFile[$x]) == "header") {...}
Using strpos() can help you check if word "header" exists anywhere in a string. If the given word does not exists than it will return false:
if (strpos($arrayFile[$x], "header") !== false) {...}
Is it possible to write a regex which would take input like 'sqrt(2 * (2+2)) + sin(pi/6)' and transform it into '\sqrt{2 \cdot (2+2)} + \sin(\pi/6)'?
The problem is the 'sqrt' and parentheses in it. It is obvious I can't simply use something like this:
/sqrt\((.?)\)/ -> \\sqrt{$1}
because this code would create something like this '\sqrt{2 \cdot (2+2)) + \sin(\pi/6}'.
My solution: it simply go throw the string converted to char array and tests if a current substring starts with $latex, if it does second for-cycle go from this point in different direction and by parentheses decides where the function starts and ends. (startsWith function)
Code:
public static function formatFunction($function, $latex, $input) {
$input = preg_replace("/" . $function . "\(/", $latex . "{", $input);
$arr = str_split($input);
$inGap = false;
$gap = 0;
for ($i = count($arr) - 1; $i >= 0; $i--) {
if (startsWith(substr($input, $i), $latex)) {
for ($x = $i; $x < count($arr); $x++) {
if ($arr[$x] == "(" || $arr[$x] == "{") { $gap++; $inGap = true; }
else if ($arr[$x] == ")" || $arr[$x] == "}") { $gap--; }
if ($inGap && $gap == 0) {
$arr[$x] = "}";
$inGap = false;
break;
}
}
}
$gap = 0;
}
return implode($arr);
}
Use:
self::formatFunction("sqrt", "\\sqrt",
"sqrt(25 + sqrt(16 - sqrt(49)) + (7 + 1)) + sin(pi/2)");
Output:
\sqrt{25+\sqrt{16-\sqrt{49}}+(7+1)}+\sin (\pi/2)
Note: sin and pi aren't formated by this code, it's only str_replace function...
In general, no regular expression can effectively handle nested parentheses. Sorry to be the bearer of bad news! The MathJAX parser library can interpret LaTeX equations and you could probably add a custom output routine to do what you want.
For TeX questions, you can also try http://tex.stackexchange.com .
Some time ago i soved a similar problem in such way. Maybe it will be helpful for you
$str = 'sqrt((2 * (2+2)) + sin(pi/(6+7)))';
$from = []; // parentheses content
$to = []; // patterns for replace #<number>
$brackets = [['(', ')'], ['{', '}'], ['[', ']']]; // new parentheses for every level
$level = 0;
$count = 1; // count or replace made
while($count) {
$str = preg_replace_callback('(\(([^()]+)\))',
function ($m) use (&$to, &$from, $brackets, $level) {
array_unshift($to, $brackets[$level][0] . $m[1] . $brackets[$level][1]);
$i = '#' . (count($to)-1); // pattern for future replace.
// here it '#1', '#2'.
// Make it so they will be unique
array_unshift($from, $i);
return $i; }, $str, -1, $count);
$level++;
}
echo str_replace($from, $to, $str); // return content back
// sqrt[{2 * (2+2)} + sin{pi/(6+7)}]
I forgot all details, but it, seems, works
I want to remove last digit from decimal number in PHP.
Lets say I have 14.153. I want it to be 14.15. I will do this step till my number is no longer decimal.
I think this should work:
<?php
$num = 14.153;
$strnum = (string)$num;
$parts = explode('.', $num);
// $parts[0] = 14;
// $parts[1] = 153;
$decimalPoints = strlen($parts[1]);
// $decimalPoints = 3
if($decimalPoints > 0)
{
for($i=0 ; $i<=$decimalPoints ; $i++)
{
// substring($strnum, 0, 0); causes an empty result so we want to avoid it
if($i > 0)
{
echo substr($strnum, 0, '-'.$i).'<br>';
}
else
{
echo $strnum.'<br>';
}
}
}
?>
echo round(14.153, 2); // 14.15
The round second parameter sets the number of digits.
You can try this.
Live DEMO
<?php
$number = 14.153;
echo number_format($number,2);
Is there a easier/better way to get every second hour than this
if(date("H")=='00'){$chart_updates = '|02|04|06|08|10|12|14|16|18|20|22|00';}
if(date("H")=='01'){$chart_updates = '|03|05|07|09|11|13|15|17|19|19|23|01';}
if(date("H")=='02'){$chart_updates = '|04|06|08|10|12|14|16|18|20|21|00|02';}
if(date("H")=='03'){$chart_updates = '|05|07|09|11|13|15|17|19|21|23|01|03';}
if(date("H")=='04'){$chart_updates = '|06|08|10|12|14|16|18|20|22|00|02|04';}
if(date("H")=='05'){$chart_updates = '|07|09|11|13|15|17|19|21|23|01|03|05';}
if(date("H")=='06'){$chart_updates = '|08|10|12|14|16|18|20|22|00|02|04|06';}
if(date("H")=='07'){$chart_updates = '|09|11|13|15|17|19|21|23|01|03|05|07';}
if(date("H")=='08'){$chart_updates = '|10|12|14|16|18|20|22|00|02|04|06|08';}
if(date("H")=='09'){$chart_updates = '|11|13|15|17|19|21|23|01|03|05|07|09';}
if(date("H")=='10'){$chart_updates = '|12|14|16|18|20|22|00|02|04|06|08|10';}
if(date("H")=='11'){$chart_updates = '|13|15|17|19|21|23|01|03|05|07|09|11';}
if(date("H")=='12'){$chart_updates = '|14|16|18|20|22|00|02|04|06|08|10|12';}
if(date("H")=='13'){$chart_updates = '|15|07|19|21|23|01|03|05|07|09|11|13';}
if(date("H")=='14'){$chart_updates = '|16|08|20|22|00|02|04|06|08|10|12|14';}
if(date("H")=='15'){$chart_updates = '|17|09|21|23|01|03|05|07|09|11|13|15';}
if(date("H")=='16'){$chart_updates = '|18|20|22|00|02|04|06|08|10|12|16|16';}
if(date("H")=='17'){$chart_updates = '|19|21|23|01|03|05|07|09|11|13|15|17';}
if(date("H")=='18'){$chart_updates = '|20|22|00|02|04|06|08|10|12|14|16|18';}
if(date("H")=='19'){$chart_updates = '|21|23|01|03|05|07|09|11|13|15|17|19';}
if(date("H")=='20'){$chart_updates = '|22|00|02|04|06|08|10|12|14|16|18|20';}
if(date("H")=='21'){$chart_updates = '|23|01|03|05|07|09|11|13|15|17|19|21';}
if(date("H")=='22'){$chart_updates = '|00|02|04|06|08|10|12|14|16|18|20|22';}
if(date("H")=='23'){$chart_updates = '|01|03|05|07|09|11|13|15|17|19|21|23';}
I need this for google charts and wanted to check if this way is stupid.
1) take the current hour
2) mod2 (there are only two different sets of numbers, odd and even)
3) build array of hours
4) sort array by value
5) split array where the original hour was, and recombine.
$h = date("H");
$line = '';
for($i=0; $i<=24; $i++)
{
if($i % 2 == $h % 2)
$line .= '|' . ($i < 10 ? '0'.$i : $i);
}
One way is to create an array with keys:
$theHour['00'] = '|02|04|06|08|10|12|14|16|18|20|22|00';
Then you can call it like this:
$chart_updates = $theHour[date("H")];
There is also probably a better way to generate this too, but since you already typed it out, its there.. It would just suck if you want to make a change.
Nice code :)
There's actually much easier way to do this in php:
$chars = array();
$start = date("H")+2;
for( $i = 0; $i < 12; $i++){
$chars[] = str_pad( ($start+2*$i)%24, 2, '0', STR_PAD_LEFT);
}
$chart_updates = '|' . implode( '|', $chars);
function helper_add($h,$plus=0){
if($h+$plus > 23){
return $h+$plus-24;
}
return $h+$plus;
}
function helper_10($in){
return $in < 10 ? '0'.$in : $in;
}
function getchartupdates(){
$now = date('G');
for($i=($now%2==0?0:1); $i<=24 ;$i+=2)
$res[] = helper_10(helper_add($now,$i));
return '|'.implode('|',$res);
}
used this to test it !