store bigint in php variable - php

I wrote a function to add a comma to every 8 zero of my number
I need to store value in PHP variable or array, but it's saved as "1.0E+30"
here is my PHP code:
function SplitHex($number) {
$number_split = str_split($number,1);
$number_split_revers = array_reverse($number_split);
$i = 0;
foreach ($number_split_revers as $key => $value ) {
if ( $value == 0) {
$i++;
if ( $i == 8 ) {
$number_split_revers[$key] = str_replace(0,",0",$value);
$i=0;
}
}
}
$final = '';
$number_final = array_reverse($number_split_revers);
foreach ($number_final as $value ) {
$final .= $value;
}
//$final = strval(implode("",$number_final));
return $final;
and I call the function :
$test[2] = SplitHex(1000000000000000000000000000000);
var_dump ($test);
print_r ($test);
the output of echo print_r var_dump are all same :
1.0E+30
but it must be 1000000,00000000,00000000,00000000
I searched a lot but couldn't find the right solution for this problem

FYI,
if the number if too long, it can not fit into 32 integer format in php, so it store it in float.
So you can not see that integer value if it exceed PHP_INT_MAX size.
But this is an alternative for this,
$test[2] = number_format(SplitHex(1000000000000000000000000000000),0,null,'');
var_dump ($test);
print_r ($test);
Give it a try, it should work.

Related

How to determine if an array has any elements or not?

How do I find if an array has one or more elements?
I need to execute a block of code where the size of the array is greater than zero.
if ($result > 0) {
// Here is the code body which I want to execute
}
else {
// Here is some other code
}
You can use the count() or sizeof() PHP functions:
if (sizeof($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
Or you can use:
if (count($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
count — Count all elements in an array, or something in an object
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Counts all elements in an array, or something in an object.
Example:
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
In your case, it is like:
if (count($array) > 0)
{
// Execute some block of code here
}
If you want to only check if the array is not empty, you should use empty() - it is much faster than count(), and it is also more readable:
if (!empty($result)) {
// ...
} else {
// ...
}
You could avoid length retrieve and check using a simple foreach:
foreach($result as $key=>$value) {
echo $value;
}
#Sajid Mehmood in PHP we have count() to count the length of an array,
when count() returns 0 that means that array is empty
Let’s take an example for your understanding:
<?php
$arr1 = array(1); // With one value which will give 1 count
$arr2 = array(); // With no value which will give 0 count
// Now I want that the array which has greater than 0 count should print other wise not so
if (count($arr1)) {
print_r($arr1);
}
else {
echo "Sorry, array1 has 0 count";
}
if (count($arr2)) {
print_r($arr2);
}
else {
echo "Sorry, array2 has 0 count";
}
Pro Tip:
If you are sure that:
the variable exists (isset) AND
the variable type is an array (is_array) ...might be true of all is_iterables, but I haven't researched that extension of the question scope.
Then you don't need to call any functions. An array with one or more elements has a boolean value of true. An array with no elements has a boolean value of false.
Code: (Demo)
var_export((bool)[]);
echo "\n";
var_export((bool)['not empty']);
echo "\n";
var_export((bool)[0]);
echo "\n";
var_export((bool)[null]);
echo "\n";
var_export((bool)[false]);
echo "\n";
$noElements = [];
if ($noElements) {
echo 'not empty';
} else {
echo 'empty';
}
Output:
false
true
true
true
true
empty
For those who start with the array in PHP presented it this way:
more information here
//Array
$result = array(1,2,3,4);
//Count all the elements of an array or something of an object
if (count($result) > 0) {
print_r($result);
}
// Or
// Determines if a variable is empty
if (!empty($result)) {
print_r($result);
}
// Or
// sizeof - Alias of count ()
if (sizeof($result)) {
print_r($result);
}
<pre>
$ii = 1;
$arry_count = count($args);
foreach ( $args as $post)
{
if( $ii == $arry_count )
{
$last = 'blog_last_item';
}
echo $last;
$ii++;
}
</pre>

Remove Duplicate Values from an array with ignoring last two characters

I am working on a small php script, currently i have an array like this
[0] yassine#m, [1] yassine#f, [2] Dolmi#m , [3] yassine#l
I want PHP to check if there is a duplicated element (yassine in this case) and return something like this.
[0] yassine , [1] Dolmi#m
array_unique won't work. And i really don't have any clue how to solve this. If looked for a solution on the internet but doesnt seem to find it. Anyone can help Please ?
I think this may work for you.
First sort array by value, then use combination of substr(), strpos() and array_push() to create new array according to your need
then remove duplicate value using array_unique()
<?php
$oldarray = array("suman#1","suman#2","suman#3","sujan#1","suresh#2","");
// first sort array by value so matching value comes together
asort($oldarray);
$newarray = array();
$count = count($oldarray);
for($i=0; $i < $count-1; $i++){
$a = $oldarray[$i];
$b = $oldarray[$i+1];
if($i == 0)
$c = "";
else
$c = $oldarray[$i-1];
if(substr($a,0,strpos($a,"#")) == substr($b,0,strpos($b,"#")) || substr($a,0,strpos($a,"#")) == substr($c,0,strpos($c,"#")) ){
array_push($newarray,substr($a,0,strpos($a,"#")));
}
else
array_push($newarray,$a);
}
print_r($oldarray);
// now remove duplicate value from new array
$newarray = array_unique($newarray);
print_r($newarray);
?>
Check following solution
http://ideone.com/fork/kJlLbs
<?php
function generateUniqueList ($arr){
$ret = array();
foreach ($arr as $value) {
$key = explode("#", $value)[0];
if (array_key_exists($key, $ret)) {
$ret[$key] = $key;
}
else {
$ret[$key] = $value;
}
}
return array_values($ret);
}
$arr = array("yassine#m","yassine#f","Dolmi#m", "yassine#l");
$list = generateUniqueList ($arr);
print_r($list);

Sorting PHP array without ksort

I am trying to manually sort a PHP array without making use of ksort.
This is how my code looks at the moment:
function my_ksort(&$arg){
foreach($arg as $key1 => $value1){
foreach($arg as $key2 => $value2){
if($key1 > $key2){
$aux = $value2;
$arg[$key2] = $value1;
$arg[$key1] = $aux;
}
}
}
}
It doesn't sort, I can't figure out how to make it sort.
You could try this:
function my_ksort(&$arg)
{
$keys=array_keys($arg);
sort($keys);
foreach($keys as $key)
{
$val=$arg[$key];
unset($arg[$key]);
$arg[$key]=$val;
}
}
I'm sorting the keys separately and then deleting the elements one-by-one and appending them to the end, in ascending order.
I'm using another sorting function (sort()), but if you want to eliminate all available sorting functions from your emulation, sort() is much easier to emulate. In fact, #crypticous's algorithm does just that!
This function return array in ASC. Take in consideration that I'm using goto which is supported in (PHP 5 >= 5.3.0)
function ascending_array($array){
if (!is_array($array)){
$array = explode(",", $array);
}
$new = array();
$flag = true;
iter:
$array = array_values($array); // recount array values with new offsets
(isset($min["max"])) ? $min["value"] = $min["max"] : $min["value"] = $array[0];
$min["offset"] = 0;
for ($i=0;$i<count($array);$i++){
if ($array[$i] < $min["value"]){ // redefine min values each time if statement executed
$min["value"] = $array[$i];
$min["offset"] = $i;
}
if ($flag){ // execute only first time
if ($array[$i] > $min["value"]){ // define max value from array
$min["max"] = $array[$i];
}
$flag = false;
}
if ($i === (count($array)-1)){ // last array element
array_push($new,$min["value"]);
unset($array[$min["offset"]]);
}
}
if (count($array)!=0){
goto iter;
}
print_r($new);
}
$arr = array(50,25,98,45);
ascending_array($arr); // 25 45 50 98
PS. When I was studying php, I wrote this function and now remembered that I had it (that's why I really don't remember what I am doing in it, though fact is it's working properly and hopefully there are comments too), hope you'll enjoy :)
DEMO
I was checking some issue related to this post and i wanted to give my insight about it ! here's what i would have done to implement php's sort :
$array_res = array();
$array = array(50,25,98,45);
$i=0;
$temp = $array[0];
$key = array_search($temp, $array);
while ($i<count($array)-1){
$temp = $array[0];
for($n=0;$n<count($array) ;$n++)
{
if($array[$n]< $temp && $array[$n] != -1 )
{
$temp = $array[$n];
}
else{continue;}
}
//get the index for later deletion
$key = array_search($temp, $array);
array_push($array_res, $temp);
/// flag on those which were ordered
$array[$key] =-1;
$i++;
}
// lastly append the highest number
for($n=0;$n<count($array) ;$n++)
{
if ($array[$n] != -1)
array_push($array_res, $array[$n]);
}
// display the results
print_r($array_res);
This code will display : Array
(
[0] => 25
[1] => 45
[2] => 50
[3] => 98
)
Short and sweet
function custom_ksort($arg)
{
$keys = array_keys($arg);
sort($keys);
foreach($keys as $newV)
{
$newArr[$newV] = $arg[$newV];
}
return $newArr;
}
It looks like your issue is that you're changing "temporary" characters $key1 and $key2 but not the actual arrays. You have to change $arg, not just $key1 and $key2.
Try something like:
$arr = Array(3=>"a",7=>"b");
print_r( $arr );
foreach( $arr as $k=>$v ){
unset($arr[$k]);
$arr[$k+1] = $v;
}
print_r($arr);

get values from multidimensional array

I have a script that creates an array in the following format
$named_array["vehicles"][0]['vehicle'] = "i100-1 " ;
$named_array["vehicles"][1]['vehicle'] = "i100-2 " ;
$named_array["vehicles"][2]['vehicle'] = "i100-46 " ;
What I want to do later in the script is get the index value[0-1-2 etc] from $named_array
but I only have the value ( i100-1 etc) as a query option , This is so I can alter it later. What I want to achieve is something like , what is the index value of $named_array where value is i100-2
this is output to json at the end .
I hope this makes sense ! any help please ?
function complex_index_of($named_array, $val){
for($i=0, $n=count($named_array['vehicles']); $i<$n; $i++){
if ($named_array['vehicles'][$i]['vehicle'] == $val)
return $i;
}
return -1;
}
echo complex_index_of($named_array, 'i100-2 ');
// output: 1
Try something like this (maybe create a function, if you need to do it more than once)
$needle = 'i100-1';
$vIndex = -1;
foreach ($named_array["vehicles"] as $index => $data) {
if($data['vehicle'] == $needle) {
$vIndex = $index;
break;
}
}

Referencing a multidimensional array's elements based on a string without eval

Alright I'm working with a large multidimensional array which has more information in it than I need and I want to loop through it to filter the data which I'm interested in. Sadly this multidimensional array is produced dynamically and doesn't always contain the data I want, so I have to use logic like:
if(isset($ar['b']['ba']['baa'])){
echo '<h3>'.$ar['b']['ba']['baa'].'</h3>';
}
if(isset($ar['b']['ba']['baba'])){
echo '<h3>'.$ar['b']['ba']['baba'].'</h3>';
}
if(isset($ar['b']['ba']['babb'])){
echo '<h3>'.$ar['b']['ba']['babb'].'</h3>';
}
The above works great but its a bit messy-looking so I converted the above to:
$refAr=array();
$refAr[]='b->ba->baa';//3
$refAr[]='b->ba->bab->baba';//4
$refAr[]='b->ba->bab->babb';//5
The above looks a lot more nice and neat and is how I want to control the script in case I need to reference different keys in the future. The problem I am having is trying to use the above format to actually reference the array. I thought variable variables would work but apparently it fails. My second attempt using eval worked but I'm not very happy with my solution. This is where I need you guys to come in, is there a better way to do this? Here's my attempt below:
<?php
$ar=array(
'a'=>array('aa'=>1,'ab'=>2),
'b'=>array(
'ba'=>array('baa'=>3,'bab'=>array('baba'=>4,'babb'=>5),'bac'=>array('baca'=>6,'bacb'=>7)),
)
);
$refAr=array();
$refAr[]='b->ba->baa';//3
$refAr[]='b->ba->bab->baba';//4
$refAr[]='b->ba->bab->babb';//5
foreach($refAr as $ref)
{
$r=explode('->',$ref);
$r="\$ar['".implode("']['",$r)."']";
echo '<h1>'.$r.'</h1>';
echo '<h3>'.$$r.'</h3>';//undefined
eval('$t='.$r.';');
echo "<h3>$t</h3>";//works but uses eval, is there a better way?
}
You can try
$ar = array();
$ar['b']['ba']['baa'] = 3;
$ar['b']['ba']['bab']['baba'] = 4;
$ar['b']['ba']['bab']['babb'] = 5;
$refAr = array();
$refAr[] = 'b->ba->baa'; // 3
$refAr[] = 'b->ba->bab->baba'; // 4
$refAr[] = 'b->ba->bab->babb'; // 5
foreach ( $refAr as $ref ) {
$t = $ar;
foreach ( explode("->", $ref) as $v ) {
if (!isset($t[$v]))
break;
$t = $t[$v];
}
is_array($t) and $t = null;
echo "<h3>$t</h3>";
}
Output
345
I decided to answer my own question. This is what I wound up using:
<?php
//Sample PHP representation of dynamically-pulled JSON data from an untrusted source
$ar=array(
'a'=>array('aa'=>1,'ab'=>2),
'b'=>array(
'ba'=>array('baa'=>3,'bab'=>array('baba'=>4,'babb'=>5),'bac'=>array('baca'=>6,'bacb'=>7)),
)
);
//Reusable function
function resolveReference($ar,&$ref)
{
$t = $ar;
foreach ( explode('->',$ref) as $v )
{
if (!array_key_exists($v,$t)){$ref=null;return false;}
$t = $t[$v];
}
$ref=$t;
return true;
}
//The references I'm interested in but don't know if my dynamic data will contain these keys every time
$refAr=array();
$refAr[]='b->ba->baa';
$refAr[]='b->ba->bab->baba';
$refAr[]='b->ba->bab->babb';
$refAr[]='b->doesnt->exist';
foreach($refAr as $ref)
{
echo '<h1>'.$ref.'</h1>';
if(resolveReference($ar,$ref))
{
echo '<h3><span style="color:blue;">'.$ref.'</span></h3>';
}else{
echo '<h3><span style="color:red;">Alternative text for non-existent expected reference</span></h3>';
}
}

Categories