How To Find a Value and Use it in PHP? - php

My goal is to do this :
Get the value from variable
Check the value
Change to thousands depending on the value
Use the new value.
Example :
$input = 12345
//Code to detect input is in thousands or hundreds
$input = 12345 ==> $change = 12000 / 10000
My Goal is to achieve $change, where the code could detect the input and return whether or not it's in hundreds or thousands and so forth.
The Answer I arrived in after combining all of your opinions :
$maxBarChart= max($countBarChart1,$countBarChart2,$countBarChart3); //The inputs
$length = strlen(strval($maxBarChart)); // Get the length
//Checks
if($length==1){
$numberBarChart = floor($maxBarChart/1);
$totalBarChart = ($numberBarChart*1)+5;
}
elseif($length==2){
$numberBarChart = floor($maxBarChart/10);
$totalBarChart = ($numberBarChart*10)+50;
}
elseif($length==3){
$numberBarChart = floor($maxBarChart/100);
$totalBarChart = ($numberBarChart*100)+500;
}
elseif($length==4){
$numberBarChart = floor($maxBarChart/1000);
$totalBarChart = ($numberBarChart*1000)+5000;
}
elseif($length==5){
$numberBarChart = floor($maxBarChart/10000);
$totalBarChart = ($numberBarChart*10000)+50000;
}
elseif($length==6){
$numberBarChart = floor($maxBarChart/100000);
$totalBarChart = ($numberBarChart*100000)+500000;
}
elseif($length==7){
$numberBarChart = floor($maxBarChart/1000000);
$totalBarChart = ($numberBarChart*1000000)+5000000;
}
elseif($length==8){
$numberBarChart = floor($maxBarChart/10000000);
$totalBarChart = ($numberBarChart*10000000)+50000000;
}
elseif($length==9){
$numberBarChart = floor($maxBarChart/100000000);
$totalBarChart = ($numberBarChart*100000000)+500000000;
}
elseif($length==10){
$numberBarChart = floor($maxBarChart/1000000000);
$totalBarChart = ($numberBarChart*1000000000)+5000000000;
}
Although it's crude and inefficent but the code works and achieved what I was aiming for, the post was made to find out about the floor function and strlen idea.
Thank You Everyone who advised and answered my post.

Use the floor() function and divide by 1000 to get the number of thousands in your input :
$change = floor($input/1000) //12
The same way, you get the number of hundreds :
$change = floor($input/100) //123
If the result is 0 (with an input of 143 for example), that means there is no thousand in it. You should divide by 10 and try it out with 100 :
if(floor($input/1000) == 0) {
if(floor($input/100 == 0)) {
//...
}
} else {
$change = floor($input/1000);
}
You may do the same into a for loop with a step of /10 to try thousands, hundreds etc.
If you need to get the rest, use the modulo operator.
For example, 120 % 100 = 20. Also, 12345 % 10000 = 2345.

Related

how to generate a random base64 number to power of 11

im trying to work on urls, so i need a random base64 to the power of 11 number, which changes every time you refresh the page.
Im working in php.
any help would be great,
many thanks.
not sure how to go about but maybe somthing like bellow?
function toChars($number) {
$res = base_convert($number, 10,26);
$res = strtr($res,'0123456789','qrstuvxwyz');
return $res;
}
or
$res = ('0123456789','abcdefghijklmnopqrstuvxwyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
then randomly select from that till you get a 11 digit number aka(base64 to power of 11)
and echo the number here $random_base64_number = ?
Dont worry figured it out.
function base62() {
$index = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
$res = '';
for ($x = 1; $x <= 11; $x++) {
$res .= $index[rand(1, strlen($index))];
}
echo "The number is: $res <br>";
}

Is there a faster way than array_diff in PHP

I have a set of numbers from MySQL within the range 1000 0000 (8 digits) to 9 999 999 999 (10 digits). It's supposed to be consecutive, but there are missing numbers. I need to know which numbers are missing.
The range is huge. At first I was going to use PHP to do this:
//MySqli Select Query
$results = $mysqli->query("SELECT `OCLC Number` FROM `MARC Records by Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
$n_array[] = $row["OCLC Number"];
}
d($n_array);
foreach($n_array as $k => $val) {
print $val . " ";
}
/* 8 digits */
$counter = 10000000;
$master_array = array();
/* 10 digits */
while ($counter <= 9999999999 ) {
$master_array[] = $counter;
$counter++;
d($master_array);
}
d($master_array);
$missing_numbers_ar = array_diff ($master_array, $n_array);
d($missing_numbers_ar);
d() is a custom function akin to var_dump().
However, I just realized it would take tons of time for this to be done. At the 15 minute mark, $master_array is being populated with only 4000 numbers.
How can I do this in a quicker way? MySQL-only or MySQL-and-PHP solutions both welcome. If the optimal solution depends on how many numbers are missing, please let me know how so. Tq.
Your d() probably is the cause of slowness, please remove it, and make small changes in your code
while($row = $results->fetch_assoc()) {
$n_array[$row["OCLC Number"]] = 1;
}
and
$missing_numbers_ar = [];
while ($counter++ <= 9999999999 ) {
if (empty($n_array[$counter])) {
$missing_numbers_ar[] = $counter;
}
}
If the following is still slow I would be surprised. I also just noticed it is similar to #Hieu Vo's answer.
// Make sure the data is returned in order by adding
// an `ORDER BY ...` clause.
$results = $mysqli->query("SELECT `OCLC Number`
FROM `MARC Records by Number`
ORDER BY `OCLC Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
// Add the "OCLC Number" as a key to the array.
$n_array[$row["OCLC Number"]] = $row["OCLC Number"];
}
// assume the first array key is in fact correct
$i = key($n_array);
// get the last key, also assume it is not missing.
end($n_array);
$max = key($n_array);
// reset the array (should not be needed)
reset($n_array);
do {
if (! $n_array[$i]) {
echo 'Missing key:['.$i.']<br />';
// flush the data to the page as you go.
flush();
}
} while(++$i <= $max);

How to get Fields Flags Name with SQL Query

Actually I want to Display Flags Name of all fields which is belongs to a table. This is Our script, from which i am performing this action.
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("DatabaseName");
$result = mysql_query("SELECT * FROM Table_Name");
$fields = mysql_num_fields($result);
for ($i=0; $i < $fields; $i++) {
$flags = mysql_field_flags($result, $i); echo $flags . "<br>";
}
mysql_free_result($result);
mysql_close();
?>
This works well, but the problem is this script is mysql version but i want mysqli version of the script. Is there any way to perform the same action by mysqli version of the script.
and also the question is - this script is using offset value in for loop. Is there any to way to display flags value without offset value
OR Insetead of using offset value can we use field name ?
this will fetch the flags
$mysqli=new mysqli('localhost','root','','database');
$result=$mysqli->query('SELECT * FROM table');
while($meta = mysqli_fetch_field($result)){
$flags=$meta->flags;
echo $flags."<br>";
print_r(get_flag1($flags));
echo '<br/>';
print_r(get_flag2($flags));
echo '<br/>';
}
function get_flag1($flag_value){
$result['NOT_NULL_FLAG'] = 1&$flag_value?1:0;
$result['PRI_KEY_FLAG'] = 2&$flag_value?1:0;
$result['UNIQUE_KEY_FLAG'] = 4&$flag_value?1:0;
$result['BLOB_FLAG'] = 16&$flag_value?1:0;
$result['UNSIGNED_FLAG'] = 32&$flag_value?1:0;
$result['ZEROFILL_FLAG'] = 64&$flag_value?1:0;
$result['BINARY_FLAG'] = 128&$flag_value?1:0;
$result['ENUM_FLAG'] = 256&$flag_value?1:0;
$result['AUTO_INCREMENT_FLAG'] = 512&$flag_value?1:0;
$result['TIMESTAMP_FLAG'] = 1024&$flag_value?1:0;
$result['SET_FLAG'] = 2048&$flag_value?1:0;
$result['NUM_FLAG'] = 32768&$flag_value?1:0;
$result['PART_KEY_FLAG'] = 16384&$flag_value?1:0;
$result['GROUP_FLAG'] = 32768&$flag_value?1:0;
$result['UNIQUE_FLAG'] = 65536&$flag_value?1:0;
return $result;
}
function get_flag2($flag_value){
if(1&$flag_value)
$result[]='NOT_NULL_FLAG';
if(2&$flag_value)
$result[]='PRI_KEY_FLAG';
if(4&$flag_value)
$result[]='UNIQUE_KEY_FLAG';
if(16&$flag_value)
$result[]='BLOB_FLAG';
if(32&$flag_value)
$result[]='UNSIGNED_FLAG';
if(64&$flag_value)
$result[]='ZEROFILL_FLAG';
if(128&$flag_value)
$result[]='BINARY_FLAG';
if(256&$flag_value)
$result[]='ENUM_FLAG';
if(512&$flag_value)
$result[]='AUTO_INCREMENT_FLAG';
if(1024&$flag_value)
$result[]='TIMESTAMP_FLAG';
if(2048&$flag_value)
$result[]='SET_FLAG';
if(32768&$flag_value)
$result[]='NUM_FLAG';
if(16384&$flag_value)
$result[]='PART_KEY_FLAG';
if(32768&$flag_value)
$result[]='GROUP_FLAG';
if(65536&$flag_value)
$result[]='UNIQUE_FLAG';
return $result;
}
how it work
using & with these values to check the wanted flag it will output 0 if the flag is off or the value if the flag is on
for example to check UNIQUE_KEY_FLAG use $flags_value&4 it will output 0 if it off or 4 if it on
NOT_NULL_FLAG = 1
PRI_KEY_FLAG = 2
UNIQUE_KEY_FLAG = 4
BLOB_FLAG = 16
UNSIGNED_FLAG = 32
ZEROFILL_FLAG = 64
BINARY_FLAG = 128
ENUM_FLAG = 256
AUTO_INCREMENT_FLAG = 512
TIMESTAMP_FLAG = 1024
SET_FLAG = 2048
NUM_FLAG = 32768
PART_KEY_FLAG = 16384
GROUP_FLAG = 32768
UNIQUE_FLAG = 65536
explain
the flag is binary number like 10110011 every bit represent a flag state on or off 0 for off and 1 for on
for example to check unique key flag it's the third bit so when you use the and operator between 100B and 10110011B the result will be all zero except the wanted bit
so if this bit is zero all the number will be zero and this mean false to php
and if it's one the result will be 100B in php any number not zero will mean true to php
Try something inline with this
if($field_flags == false) {
for($j=0; $j<$num_fields; $j++) {
$field_flags[$j] = mysqli_fetch_field_direct($result, $j);
if(strpos($field_flags[$j]->flags, 'NOT_NULL') !== false) {
//Do something here
} else {
//Do something else
}
}
or see this
How can this be done with the same result using mysqli?

Comparison Opeartor seemingly not working

I am trying to compare two values but when I do it does not appear to work. I know what the values are so it should be reporting true. Even worse, if I take either one of the variables out and put the number in it works.
$data = simplexml_load_file('xml/heroes/hero.xml')
or die("Error: Cannot create object");
$hme = $data->hes->he->maxen;
$hce = $data->hes->he->curen;
$hac = $data->hes->he->lastac;
echo $hce . ' should not be greater than ' . $hme;
if($hce > $hme){
echo 'should be working';
}
Outputs:
773 should not be greater than 20
I think your variable are like this
$hce = "773";
$hme = "20";
Before comparing them do intval
if(intval($hme)>intval($hce))
Cast your strings to integers:
$hme = (int)$data->hes->he->maxen;
$hce = (int)$data->hes->he->curen;
$hac = (int)$data->hes->he->lastac;
I think you took them as strings.I think you need to convert them to integer.
Simple function to do that:
int atoi(char *s)
{
int val = 0;
while (*s)
{
val *= 10;
val += (*s) - '0';
s++;
}
return val;
}

How to define trends according to some values?

I am trying to to mark some trends, so I have 1 as the lowest and 5 as the biggest value.
So for example,
I may have the following case:
5,4,5,5 (UP)
3,4, (UP)
4,3,3 (DOWN)
4,4,4,4, (FLAT - this is OK for all same numbers)
I am planning to have unlimited number of ordered values as input, an as an output I will just show an (UP), (DOWN), or (FLAT) image.
Any ideas on how I can achieve this?
Sorry if I am not descriptive enough.
Thank you all for you time.
Use least square fit to calculate the "slope" of the values.
function leastSquareFit(array $values) {
$x_sum = array_sum(array_keys($values));
$y_sum = array_sum($values);
$meanX = $x_sum / count($values);
$meanY = $y_sum / count($values);
// calculate sums
$mBase = $mDivisor = 0.0;
foreach($values as $i => $value) {
$mBase += ($i - $meanX) * ($value - $meanY);
$mDivisor += ($i - $meanX) * ($i - $meanX);
}
// calculate slope
$slope = $mBase / $mDivisor;
return $slope;
} // function leastSquareFit()
$trend = leastSquareFit(array(5,4,5,5));
(Untested)
If the slope is positive, the trend is upwards; if negative, it's downwards. Use your own judgement to decide what margin (positive or negative) is considered flat.
A little bit hard to answer based on the limited info you provide, but assuming that:
if there's no movement at all the trend is FLAT,
otherwise, the trend is the last direction of movement,
then this code should work:
$input = array();
$previousValue = false;
$trend = 'FLAT';
foreach( $input as $currentValue ) {
if( $previousValue !== false ) {
if( $currentValue > $previousValue ) {
$trend = 'UP';
} elseif( $currentValue < $previousValue ) {
$trend = 'DOWN';
}
}
$previousValue = $currentValue;
}
For your examples :
Calculate longest increasing subsequence, A
Calulate longest decreasing subsequence , B
Going by your logic, if length of A is larger than B , its an UP , else DOWN.
You will also need to keep track of all equals using one boolean variable to mark FLAT trend.
Query :
What trend would be :
3,4,5,4,3 ?
3,4,4,4,3 ?
1,2,3,4,4,3,2,2,1 ?
Then the logic might need some alterations depending upon what your requirements are .
I'm not sure if i understand your problem totally but I would put the values in an array and use a code like this (written in pseudocode):
int i = 0;
String trend = "FLAT":
while(i<length(array)) {
if(array(i)<array(i+1)) {
trend = "UP";
}
else if(array(i)>array(i+1) {
trend = "DOWN";
}
i++;
}
EDIT: this would obviously only display the trend of the latest alteration
one would also may count the number of times the trend is up or down and determine the overall trend by that values
echo foo(array(5,4,5,5)); // UP
echo foo(array(3,4)); // UP
echo foo(array(4,3,3)); // DOWN
echo foo(array(4,4,4,4)); // FLAT
function foo($seq)
{
if (count(array_unique($seq)) === 1)
return 'FLAT';
$trend = NULL;
$count = count($seq);
$prev = $seq[0];
for ($i = 1; $i < $count; $i++)
{
if ($prev < $seq[$i])
{
$trend = 'UP';
}
if ($prev > $seq[$i])
{
$trend = 'DOWN';
}
$prev = $seq[$i];
}
return $trend;
}
I used the code from #liquorvicar to determine Google search page rank trends, but added some extra trend values to make it more accurate:
nochange - no change
better (higher google position = lower number)
worse (lower google position = higher number)
I also added extra checks when the last value had no change, but taking in account the previous changes i.e.
worsenochange (no change, previouse was worse - lower number)
betternochange (no change, previouse was better - lower number)
I used these values to display a range of trend icons:
$_trendIndicator="<img title="trend" width="16" src="/include/main/images/trend-'. $this->getTrend($_positions). '-icon.png">";
private function getTrend($_positions)
{
// calculate trend based on last value
//
$_previousValue = false;
$_trend = 'nochange';
foreach( $_positions as $_currentValue ) {
if( $_previousValue !== false ) {
if( $_currentValue > $_previousValue ) {
$_trend = 'better';
} elseif( $_currentValue < $_previousValue ) {
$_trend = 'worse';
}
if ($_trend==='worse' && ($_previousValue == $_currentValue)) {$_trend = 'worsenochange';}
if ($_trend==='better' && ($_previousValue == $_currentValue)) {$_trend = 'betternochange';}
}
$_previousValue = $_currentValue;
}
return $_trend;
}

Categories