Can you solve this in brief code? - php

there are 10 variables. say $var1, $var2, $var3, $var4,....$var10
and a $count variable. what I am looking for is if all variables are set then $count = 10+1 or if 9 variables only set then $count=9+1 or if 8 variables only set then $count=8+1 and so on last up to 1 variable(for one variable is set then $count = 1+1).
I know do this with If, Else if and else but I need to write too much line of code.
Does any one know how to do this in brief code??

You can achieve this using variable variables in PHP:
$count = 1;
for ($i = 1; $i <= 10; $i++)
{
if ( isset( ${'var'.$i} ) ) $count++;
}

Try this (untested):
$arr = array($var1, $var2, $var3, $var4, $var5, $var6, $var7, $var8, $var9, $var10);
$count = 1;
foreach ($arr as $v)
{
if (isset($v))
$count++;
}

<?php
...
$countarr = compact('var1', 'var2', ..., 'var10');
$count = count($countarr) + 1;
?>

Er... Are you aware that PHP allows to use loops...
<?php
$var1 = 100;
$var4 = 200;
$var9 = 600;
$count = 0;
for($i=1; $i<=10; $i++){
if( isset(${"var$i"}) ){
$count++;
}
}
echo $count;
?>
... and arrays?
<?php
$var = array(100, 200, 600);
$count = count($var);
echo $count;
?>
Answer to Boreadlid's remarks
You should note that unsetting an array element is not the same as setting it to NULL. This code:
<?php
$data = array(10, 20, 30);
$data[1] = NULL;
unset($data[0]);
var_dump($data);
?>
... prints this:
array(2) {
[1]=>
NULL
[2]=>
int(30)
}
... so count($data) prints 2 because it is a two element array.
Whatever the OP is trying to accomplish, he should probably be using arrays where unused values are never set to begin with. The $var1, $var2, $var3 approach will work but it's not what a skilled programmer would do. (Of course, there's nothing wrong in being a newbie.)

oh c'mon … you can do a little bit of thinking (and reading documentation) yourself.
simply take the code answered to your previous question, and use isset(${var+$i}, ${tvar+$i}) in your loop

you have 20 vars (10x "var" and 10x "tvar"):
bool[] vars = new bool[10];
bool[] tvars = new bool[10];
i don't get your +1 part in $count... but what about:
int count = 1; //includes the always needed +1 part
for(int i=0;i<10;i++)
if(vars[i] && tvars[i])
count += i+1; //so 0 => 1
??

Related

PHP create unique value compared to values from object

I need to create a unique value for $total, to be different from all other values from received object. It should compare total with order_amount from object, and then if it is the same, it should increase its value by 0.00000001, and then check again through that object to see if it matches again with another order_amount. The end result should be a unique value, with minimal increase compared to the starting $total value. All values are set to have 8 decmal places.
I have tried with the following but it won't get me the result i need. What am i doing wrong?
function unique_amount($amount, $rate) {
$total = round($amount / $rate, 8);
$other_amounts = some object...;
foreach($other_amounts as $amount) {
if ($amount->order_amount == $total) {
$total = $total + 0.00000001;
}
}
return $total;
}
<?php
define('EPSILON',0.00000001);
$total = 4.00000000;
$other_amounts = [4.00000001,4.00000000,4.00000002];
sort($other_amounts);
foreach($other_amounts as $each_amount){
if($total === $each_amount){ // $total === $each_amount->order_amount , incase of objects
$total += EPSILON;
}
}
var_dump($total);
OUTPUT
float(4.00000003)
You may add an additional break if $total < $each_amount to make it a bit more efficient.
UPDATE
To sort objects in $other_amounts based on amount, you can use usort.
usort($other_amounts,function($o1,$o2){
if($o1->order_amount < $o2->order_amount ) return -1;
else if($o1->order_amount > $o2->order_amount ) return 1;
return 0;
});
Ok, here's the solution I came up with. First I created a function to deliver random objects with random totals so I could work with, unnecessary for you but useful for the sake of this test:
function generate_objects()
{
$outputObjects = [];
for ($i=0; $i < 100; $i++) {
$object = new \stdClass();
$mainValue = random_int(1,9);
$decimalValue = random_int(1,9);
$object->order_amount = "{$mainValue}.0000000{$decimalValue}";
$outputObjects[] = $object;
}
return $outputObjects;
}
And now for the solution part, first the code, then the explanation:
function unique_amount($amount, $rate) {
$total = number_format(round($amount / $rate, 8), 4);
$searchTotal = $total;
if (strpos((string) $searchTotal, '.') !== false) {
$searchTotal = str_replace('.', '\.', $searchTotal);
}
$other_amounts = generate_objects();
$similarTotals = [];
foreach($other_amounts as $amount) {
if (preg_match("/^$searchTotal/", $amount->order_amount)) {
$similarTotals[] = $amount->order_amount;
}
}
if (!empty($similarTotals)) {
rsort($similarTotals);
$total = ($similarTotals[0] + 0.00000001);
}
// DEBUG
//echo '<pre>';
//$vars = get_defined_vars();
//unset($vars['other_amounts']);
//print_r($vars);
//die;
return $total;
}
$test = unique_amount(8,1);
echo $test;
I decided to use RegEx to find the amounts that starts with the ones I provided. Since in the exercise I provided only integers with 1-9 in the last decimal case, I tracked them and added them to one array $similarTotals.
Then I sorted this array, if not empty, descending by the values, got the first item and incremented by 0.00000001.
So, finally, returning either the $total (assuming nothing was found) or the incremented first item in the array.
PS. I did not expect this code to be this big but, well...
You can see the test here: https://3v4l.org/WGThI

PHP dynamically creating variable to split array

<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c;$i++){
$v = '$var'.$i;
$splited = list($v) = $my_array;
}
?>
input:
$my_array
But expected output:
if I echo $var0, $var1, $var2;
hello, world, howareu
How to create dynamic PHP variables based upon the array count and then convert them into a list as a string?
You do not need list for that. $$ will suit you perfectly.
$my_array = array("hello", "world", "howareu");
foreach ($my_array as $key => $val)
{
$a = 'var'.$key;
$$a = $val;
}
echo $var0,", ", $var1,", " $var2;
Take a look here - Variable variables
Added:
or if you need count and for
for ($i = 0; $i < count($my_array); $i++)
{
$a = 'var'.$i;
$$a = $my_array[$i];
}
echo $var0,", ", $var1,", " $var2;
Of course, this line echo $var0,", ", $var1,", " $var2; sucks and looks like crap :) But in order to receive EXACTLY what you want, you need to modify variables, output like I've wrote, or use some function like implode with grue ', '.
Updated:
But if you need just that output, why not to use simple implode(', ', $my_array) :)
it's a matter of the data you need to process...if it's pretty static, you don't need the second foreach() for example, since you compare the keys anyways...
foreach($datavalueas $resultdatakey=>$resultdatavalue){
if($resultdatakey== 'A'){
//stuff for a
}
if($resultdatakey== 'B'){
//stuff for b
}
}
would become
if(isset($datavalueas['A'])){
//stuff for a
}
if(isset($datavalueas['B'])){
//stuff for b
}
since the foreach uses copies of the array, which are pretty bad for the performance...
Assuming i got your question right, you could use something like:
$array = array( 'x', 'y', 'z' );
foreach ($array as $name )
$$name = rand(1,100);
var_dump($x);
the $$ is key here, the first $ implies the variable as the second $ is used as the identifier for the variable. In this case the value being iterated over in the array. Giving us 3 variables: $x, $y, $z.
-- edit:
the correct code, besides using extract():
<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i < $c;$i++){
$v = 'var'.$i;
$$v = $my_array[$i];
}
echo "$var0, $var1, $var2";
?>
You can create dynamic variables via variables variable as Mr.kovpack have stated here. In below code you can access the variables from 0 to $c-1(count of array) as per your comment to Mr.kovpack.
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
${'var'.$i} = $my_array[$i]; //Dynamic variable creation
// $splited = list($v) = $my_array;
}
echo $var0.$var1.$var2;
or you could use like below:
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
$a='var'.$i;
$$a = $my_array[$i];
}
echo $var0."-".$var1."-".$var2;
You can read more on it here

Weird PHP Behavior

<?php
$dog[] = "12";
$dog[] = "3";
for ($i = 0; $i < 2; $i++) {
$dig = $dog[i];
echo $dig;
}
?>
$dig is always null. Why?
i is not a variable, use $i
If you had error_reporting(E_ALL) on, as you should when in development, you would have caught it immediately (undefined constant).
$dig = $dog[i];
should be:
$dig = $dog[$i];
Easy. You want $dog[$i]. The PHP engine looks for a constant name i, can't find one, so resorts to looking for string. No a key with value 'i' either, so returns NULL.
your missing the $ in this line
$dig = $dog[i];
should be
$dig = $dog[$i];
you could also simplify this code by writing it this way
<?php
$dogs[] = "12";
$dogs[] = "3";
foreach($dogs as $dog) {
echo $dog;
}
?>
You want
$dig = $dog[$i];
You missed the $

Loop through variables with common name

At first glance I think you can get what I'm trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about the kind of loop I should use, not sure if a "for" loop would work. The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable. Ran into some trouble with outputting a string with a dollar sign as well. Thanks in advance!
$hello1 = "hello1";
$hello2 = "hello2";
$hello3 = "hello3";
$hello4 = "hello4";
$hello5 = "hello5";
$hello6 = "hello6";
$hello7 = "hello7";
$hello8 = "hello8";
$hello9 = "hello9";
$hello10 = "hello10";
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo $hello . $counter . "<br>";
}
It's generally frowned upon, since it makes code much harder to read and follow, but you can actually use one variable's value as another variable's name:
$foo = "bar";
$baz = "foo";
echo $$baz; // will print "bar"
$foofoo = "qux";
echo ${$baz . 'foo'}; // will print "qux"
For more info, see the PHP documentation on variable Variables.
However, as I already mentioned, this can lead to some very difficult-to-read code. Are you sure that you couldn't just use an array instead?
$hello = array(
"hello1",
"hello2",
// ... etc
);
foreach($hello as $item) {
echo $item . "<br>";
}
Try ${"hello" . $counter}
$a = "hell";
$b = "o";
$hello = "world";
echo ${$a . $b};
// output: world
You can use variable variables as:
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo ${'hello' . $counter } , '<br>';
}
as I guess u not even need to declare $hello1 = "hello1". coz the $counter is incrementing the numbers by its loop.
<?php
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo 'hello' . $counter . "\n";
}
?>
so this is enough to get the output as you want.
the output will be:-
hello1
hello2
hello3
hello4
hello5
hello6
hello7
etc...

PHP array as variable name

How to send an indexes name for php array vairable.
the array is
$array = array('Somthing'=>array('More'=>array('id'=> 34)));
and now I want to display this thing but with a variable name I don't know how to explain so I write what I want to have.
$index_name = '[Something][More][id]';
$array{$index_name};
Is it possible in any way ?
Not in one go like that. Here's how you'd do it:
$array['Something']['More']['id']
If you particularly wanted access multidimensional arrays with a single string, then you could build a function to do that:
function array_multi(Array $arr, $path) {
$parts = explode(".", $path);
$curr =& $arr;
for ($i = 0, $l = count($parts); $i < $l; ++$i) {
if (!isset($curr[$parts[$i]])) {
// path doesn't exist
return null;
} else if (($i < $l - 1) && !is_array($curr[$parts[$i]]) {
// path doesn't exist
return null;
}
$curr =& $curr[$parts[$i]];
}
return $curr;
}
// usage:
echo array_multi($array, "Something.More.id"); // 34
echo array_multi($array, "Something.More"); // array("id" => 34)
Recursive version supporting your syntax with square brackets:
$array = array('Something'=>array('More'=>array('id'=> 34)));
$string = '[Something][More][id]';
echo scan_array($string, $array);
function scan_array($string, $array) {
list($key, $rest) = preg_split('/[[\]]/', $string, 2, PREG_SPLIT_NO_EMPTY);
if ( $key && $rest ) {
return scan_array($rest, $array[$key]);
} elseif ( $key ) {
return $array[$key];
} else {
return FALSE;
}
}
Ok, I know this is how people get shot. But c'mon, eval() is not always the wrong answer.
$array = array('Something'=>array('More'=>array('id'=> 34)));
$index_name = '[Something][More][id]';
eval('$val = $array'.$index_name.';'); // Wrap in a function or something
You could do this with eval():
<?php
$array = array('Somthing'=>array('More'=>array('id'=> 34)));
$index_name = "['Somthing']['More']['id']";
$stmt='echo $array'.$index_name.';';
eval($stmt);
?>
UPDATE:
It seems some SO users are uncomfortable with the idea of using eval(). I think it makes sense to read this thread which discusses the pros and cons before deciding whether to use this in your own code.
If you've cornered yourself into needing to do something like this, there's a pretty good chance you've done something else in a poor way. There's valid reasons to do this, but not very often.
function key_path($arr, $keys) {
return $keys ? key_path($arr[array_shift($keys)], $keys) : $arr;
}
$arr['Something']['More']['id'] = 34;
$keys = array('Something', 'More', 'id');
var_dump( key_path($arr, $keys));

Categories