I created a small function that helps me build an array (i use it to populate a select2 element). It works great but it doesn't accept 0 as the starting number.
Although it is not really crucial i would really want to understand why this happens and how to fix it.
Here is the function:
function create_numstring_array($startNum, $endNum, $jumps, $sideString = NULL) {
if($startNum && $endNum) {
$data = array();
$counter = intval($startNum);
while($endNum > $counter ) {
$data["$counter"] = $counter.' '.$sideString;
$counter = $counter + $jumps;
// echo $counter."<br />";
}
return $data;
}
}
/* DOESNT WORK
echo '<pre>Code:'."<br />";
print_r(create_numstring_array(0, 9, 0.5, ''));
echo '</pre>'."<br />";
*/
/* WORKS! */
echo '<pre>Code:'."<br />";
print_r(create_numstring_array(1, 9, 0.5, ''));
echo '</pre>'."<br />";
I guess it gets stuck in this part
while($endNum > $counter) {
Since $counter = 0 but how can i overcome this?
Because (bool)0 == False. So, your code fails, because you are testing $startNum and it is treated as boolean false.
Change it to something more reasonable, for example: if (is_int($startNum) ... or functions like that (is_numeric could be candidate)
function create_numstring_array($startNum, $endNum, $jumps, $sideString = NULL){
#check for valid input
#(can be float or integer so lets end always greater than start)
if($startNum>$endNum || !is_numeric($jumps)) {
return null;
}
#create the range
$keys = range($startNum, $endNum, $jumps);
#create values with or without sideString
$values = ($sideString)
? array_map(function($a) use ($sideString){ return $a.' '.$sideString;},$keys)
: $keys;
#return the new array
return array_combine($keys,$values);
}
echo '<pre>Code:'."<br />";
print_r(create_numstring_array(0, 9, 0.5, ''));
echo '</pre>'."<br />";
Why your version is not working, is explained in the comments, so here a working version, that check for valid input and valid jumbs. (Works with float and integer). Remove/Skipp last and first entry is they are not needed.
Related
I'm new to php and am trying to write a loop that will flip a coin until exactly two heads have been flipped and then stop.
So far I've written a function for coin flipping:
function cointoss () {
$cointoss = mt_rand(0,1);
$headsimg = '<img src=""/>';
$tailsimg = '<img src=""/>';
if ($cointoss == 1){
print $headsimg;
} else {
print $tailsimg;
}
return $cointoss;
}
...but am stuck on writing the loop. I've tried a couple ways:
#this code takes forever to load
$twoheads = 0;
for ($twoheads = 1 ; $twoheads <= 20; $twoheads++) {
$cointoss = mt_rand(0,1);
cointoss ();
if ($cointoss == 1) {
do {
cointoss ();
} while ($cointoss == 1);
}
}
#one coin flips
do {
cointoss ();
} while ($cointoss == 1);
This is a for a class, and we haven't learned arrays yet, so I need to accomplish this without them.
I understand the concept of loops executing code while a condition is true, but don't understand how to write for when a condition is no longer true.
Printing from inside of "processing functions" is a bad habit to get into. You might like to declare a showCoin($toss) function for printing. In truth, I don't know if I would bother with any custom functions.
You need to declare a variable which will hold the return value from your function.
By storing the current and previous toss values, you can write a simple check if two consecutive "heads" have occurred.
Code: (Demo)
function cointoss () {
return mt_rand(0,1); // return zero or one
}
$previous_toss = null;
$toss = null;
do {
if ($toss !== null) { // only store a new "previous_toss" if not the first iteration
$previous_toss = $toss; // store last ieration's value
}
$toss = cointoss(); // get current iteration's value
echo ($toss ? '<img src="heads.jpg"/>' : '<img src="tails.jpg"/>') , "\n";
// ^^^^^- if a non-zero/non-falsey value, it is heads, else tails
} while ($previous_toss + $toss != 2);
// ^^^^^^^^^^^^^^^^^^^^^^- if 1 + 1 then 2 breaks the loop
Possible Output:
<img src="heads.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="heads.jpg"/>
<img src="heads.jpg"/>
I think the code itself that I wrote to try and get this working is pretty self explanatory. First time I'm using a while loop, I did search other similar questions, and also here yet I can't figure this one out.
Right now, the code is only running once for some reason, if for some random chance the number from array_rand is 6 then it returns yes, otherwise it won't even echo no when it should since it's inside the while loop, but clearly I'm wrong.
/**
* Check if param number is between 5 and 7
* #param {int} $number - number
*/
function check($number){
if($number >= 5 && $number <= 7){
return array('message' => 'Number is between the min and the max');
}
return false;
}
// Random numbers for testing
$info = array(1,2,3,4,5,6,7,8,9,10);
// Get a random number from the array
$info_rand = $info[array_rand($info)];
// run function by passing a random number from the array
$run_loop = check($info_rand);
// here we should keep running the function until it returns true then break, otherwise just echo no so we know it's running
while(true){
if($run_loop){
echo 'Yes';
break;
} else {
echo 'no';
}
}
https://eval.in/953478
Take a look at the following change:
/**
* Check if param number is between 5 and 7
* #param {int} $number - number
*/
function check($number){
if($number >= 5 && $number <= 7){
return array('message' => 'Number is between the min and the max');
}
return false;
}
// Random numbers for testing
$info = array(1,2,3,4,5,6,7,8,9,10);
// here we should keep running the function until it returns true then
// break, otherwise just echo no so we know it's running
while(true){
// Get a random number from the array
$info_rand = $info[array_rand($info)];
// run function by passing a random number from the array
$run_loop = check($info_rand);
if($run_loop){
echo 'Yes';
break;
} else {
echo 'no';
}
}
nothing is changing the $run_loop variable
/**
* Check if param number is between 5 and 7
* #param {int} $number - number
*/
function check($number){
if($number >= 5 && $number <= 7){
return array('message' => 'Number is between the min and the max');
}
return false;
}
// Random numbers for testing
$info = array(1,2,3,4,5,6,7,8,9,10);
// here we should keep running the function until it returns true then break, otherwise just echo no so we know it's running
while(true){
//this will randomize each time
//before it would never change
if(check($info[rand(0,count($info))])){
echo 'Yes';
break;
} else {
echo 'no';
}
}
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;
I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}
I'm trying to loop through a set of records, all of which have a "number" property. I am trying to check if there are 3 consecutive records, e.g 6, 7 and 8.
I think i'm almost there with the code below, have hit the wall though at the last stage - any help would be great!
$nums = array();
while (count($nums <= 3))
{
//run through entries (already in descending order by 'number'
foreach ($entries as $e)
{
//ignore if the number is already in the array, as duplicate numbers may exist
if (in_array($e->number, $num))
continue;
else
{
//store this number in the array
$num[] = $e->number;
}
//here i need to somehow check that the numbers stored are consecutive
}
}
function isConsecutive($array) {
return ((int)max($array)-(int)min($array) == (count($array)-1));
}
You can achieve the same result without looping, too.
If they just have to be consecutive, store a $last, and check to make sure $current == $last + 1.
If you're looking for n numbers that are consecutive, use the same, except also keep a counter of how many ones fulfilled that requirement.
$arr = Array(1,2,3,4,5,6,7,343,6543,234,23432,100,101,102,103,200,201,202,203,204);
for($i=0;$i<sizeof($arr);$i++)
{
if(isset($arr[$i+1]))
if($arr[$i]+1==$arr[$i+1])
{
if(isset($arr[$i+2]))
if($arr[$i]+2==$arr[$i+2])
{
if(isset($arr[$i+3]))
if($arr[$i]+3==$arr[$i+3])
{
echo 'I found it:',$arr[$i],'|',$arr[$i+1],'|',$arr[$i+2],'|',$arr[$i+3],'<br>';
}//if3
}//if 2
}//if 1
}
I haven't investigated it thoroughly, maybe can be improved to work faster!
This will confirm if all items of an array are consecutive either up or down.
You could update to return an array of [$up, $down] or another value instead if you need direction.
function areAllConsecutive($sequence)
{
$up = true;
$down = true;
foreach($sequence as $key => $item)
{
if($key > 0){
if(($item-1) != $prev) $up = false;
if(($item+1) != $prev) $down = false;
}
$prev = $item;
}
return $up || $down;
}
// areAllConsecutive([3,4,5,6]); // true
// areAllConsecutive([3,5,6,7]); // false
// areAllConsecutive([12,11,10,9]); // true
Here's an example that can check this requirement for a list of any size:
class MockNumber
{
public $number;
public function __construct($number)
{
$this->number = $number;
}
static public function IsListConsecutive(array $list)
{
$result = true;
foreach($list as $n)
{
if (isset($n_minus_one) && $n->number !== $n_minus_one->number + 1)
{
$result = false;
break;
}
$n_minus_one = $n;
}
return $result;
}
}
$list_consecutive = array(
new MockNumber(0)
,new MockNumber(1)
,new MockNumber(2)
,new MockNumber(3)
);
$list_not_consecutive = array(
new MockNumber(5)
,new MockNumber(1)
,new MockNumber(3)
,new MockNumber(2)
);
printf("list_consecutive %s consecutive\n", MockNumber::IsListConsecutive($list_consecutive) ? 'is' : 'is not');
// output: list_consecutive is consecutive
printf("list_not_consecutive %s consecutive\n", MockNumber::IsListConsecutive($list_not_consecutive) ? 'is' : 'is not');
// output: list_not_consecutive is not consecutive
If u don't wanna mess with any sorting, picking any of three numbers that are consecutive should give you:
- it either is adjacent to both the other numbers (diff1 = 1, diff2 = -1)
- the only number that is adjacent (diff = +-1) should comply the previous statement.
Test for the first condition. If it fails, test for the second one and under success, you've got your secuence; else the set doesn't comply.
Seems right to me. Hope it helps.
I think you need something like the following function (no need of arrays to store data)
<?php
function seqOfthree($entries) {
// entries has to be sorted descending on $e->number
$sequence = 0;
$lastNumber = 0;
foreach($entries as $e) {
if ($sequence==0 or ($e->number==$lastNumber-1)) {
$sequence--;
} else {
$sequence=1;
}
$lastNumber = $e->number;
if ($sequence ==3) {
// if you need the array of sequence you can obtain it easy
// return $records = range($lastNumber,$lastNumber+2);
return true;
}
}
// there isn't a sequence
return false;
}
function isConsecutive($array, $total_consecutive = 3, $consecutive_count = 1, $offset = 0) {
// if you run out of space, e.g. not enough array values left to full fill the required # of consecutive count
if ( $offset + ($total_consecutive - $consecutive_count ) > count($array) ) {
return false;
}
if ( $array[$offset] + 1 == $array[$offset + 1]) {
$consecutive_count+=1;
if ( $consecutive_count == $total_consecutive ) {
return true;
}
return isConsecutive($array, $total_consecutive, $consecutive_count, $offset+=1 );
} else {
return isConsecutive($array, $total_consecutive, 1, $offset+=1 );
}
}
The following function will return the index of the first of the consecutive elements, and false if none exist:
function findConsecutive(array $numbers)
{
for ($i = 0, $max = count($numbers) - 2; $i < $max; ++$i)
if ($numbers[$i] == $numbers[$i + 1] - 1 && $numbers[$i] == $numbers[$i + 2] - 2)
return $i;
return false;
}
Edit: This seemed to cause some confusion. Like strpos(), this function returns the position of the elements if any such exists. The position may be 0, which can evaluate to false. If you just need to see if they exist, then you can replace return $i; with return true;. You can also easily make it return the actual elements if you need to.
Edit 2: Fixed to actually find consecutive numbers.