Separating float digits into an array - php

So I have a decimal (5,2) that I am trying to separate into an array.
So if the number is..
123.45 = array([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
23.45 = array([0] => 0 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
3.45 = array([0] => 0 [1] => 0 [2] => 3 [3] => 4 [4] => 5 )
I have a pretty large code to do this, and I wanted to know if anyone had a simpler way of putting each digit into this array because I feel like mine is pretty convoluted.
$number = 123.35;
$number_array = explode(".", $number);
$final_array = array(0);
if(!empty(#(string)$number_array[0][0]) && !empty(#(string)$number_array[0][1]) && !empty(#(string)$number_array[0][2]))
{
$final_array[0] = #(string)$number_array[0][0];
$final_array[1] = #(string)$number_array[0][1];
$final_array[2] = #(string)$number_array[0][2];
}
elseif(!empty(#(string)$number_array[0][0]) && !empty(#(string)$number_array[0][1]) && empty(#(string)$number_array[0][2]))
{
$final_array[0] = 0;
$final_array[1] = #(string)$number_array[0][0];
$final_array[2] = #(string)$number_array[0][1];
}
elseif(!empty(#(string)$number_array[0][0]) && empty(#(string)$number_array[0][1]) && empty(#(string)$number_array[0][2]))
{
$final_array[0] = 0;
$final_array[1] = 0;
$final_array[2] = #(string)$number_array[0][0];
}
else
{
$final_array[0] = 0;
$final_array[1] = 0;
$final_array[2] = 0;
}
empty(#(string)$number_array[1][0]) ? $final_array[3] = 0 : $final_array[3] = #(string)$number_array[1][0];
empty(#(string)$number_array[1][1]) ? $final_array[4] = 0 : $final_array[4] = #(string)$number_array[1][1];

$number = str_replace('.', '', (string) 13.35);
$number = str_pad($number, 5, "0", STR_PAD_LEFT);
var_dump(str_split($number));

I think this is what you're looking for:
list($whole, $decimal) = sscanf($number, '%d.%d');
$result = str_split(sprintf('%03s',$whole) . $decimal);
Test cases:
foreach ([123.45, 23.45, 3.45] as $number) {
list($whole, $decimal) = sscanf($number, '%d.%d');
$result = str_split(sprintf('%03s',$whole).$decimal);
echo implode(', ', $result) . "\n";
}
Output:
1, 2, 3, 4, 5
0, 2, 3, 4, 5
0, 0, 3, 4, 5
Demo

You want to take a look at phps str_split() function.

Have you tried using regular expressions? That would be the best in your case..

Related

I want to make a key value pair of numeric array in PHP on the base of index

foreach($manualsArray as $manuls){
for($i=0;$i<=count($manuls);$i++){
if($i/2 == 0){
$manuls = 23;
print($manuls);
}
else{
$manualsArray= 98;
print($manualsArray);
}
print($manualsArray);
}
}
I want to create key value pairs according to index like 0 is key 1 is value 2 is key 3 is value and so on.
the sample input is write below
Array
(
[0] => Array
(
[0] => Faucet Centers
[1] => 6, 4, 13, 12, 7, 10, 14, 16, 8, 5, 9, 15, 11 in.
[2] => Flow Rate (GPM)
[3] => 1.2
[4] => Height
[5] => 5.875 in.
[6] => Max Deck Thickness
[7] => 2.25 in.
[8] => Spout Height
[9] => 3.625 in.
[10] => Spout Reach
[11] => 5 in.
)
)
You can achieve this by changing your loop to increment by 2 each time and take $i as the key and $i+1 as the value...
$output = [];
foreach($manualsArray as $manual){
$m = [];
for ( $i = 0; $i < count($manual); $i+=2 ) {
$m [$manual[$i]] = $manual[$i+1];
}
$output [] = $m;
}
print_r($output);
you can use array_chunk()
foreach($manualsArray as $manuls){
foreach( array_chunk($manuls, 2) as $pair) {
echo 'key: ' . $pair[0] . ' is value: '. $pair[1] . "<br>/n";
}
}
or if you want an associative array
$result_array = [];
foreach($manualsArray as $manuls){
foreach( array_chunk($manuls, 2) as $pair) {
$result_array[] = [$pair[0] => $pair[1]];
}
}
var_export($result_array);
https://www.php.net/manual/en/function.array-chunk.php
Use modulo for that:
<?php
$newarray = array();
foreach($yourarray[0] as $id => $val){
if($id % 2 == 0){
$last_index = $val;
}else{
$newarray[$last_index] = $val;
}
}
?>
I assume that your array is the one you have given, so it's 2-dimensional.
If not, use $yourarray instead of $yourarray[0].

How to split array in php?

I am little bit confused to get first and last value from array. And I tried to use explode()function but my logic is not working properly and very stupid logic.
My array
Array
(
[0] => 500 - 1112
[1] => 1113 - 2224
[2] => 2225 - 4446
[3] => 4446
)
I tried this way
$range = explode(',', $price_range);
$count = count($range);
if (1 == $count) {
$price_1 = $range[0];
$ranges['range1'] = explode(' - ', $price_1);
} else if (2 == $count) {
$price_1 = $range[0];
$price_2 = $range[1];
$ranges['range1'] = explode(' - ', $price_1);
$ranges['range2'] = explode(' - ', $price_2);
} else if (3 == $count) {
$price_1 = $range[0];
$price_2 = $range[1];
$price_3 = $range[2];
$ranges['range1'] = explode(' - ', $price_1);
$ranges['range2'] = explode(' - ', $price_2);
$ranges['range3'] = explode(' - ', $price_3);
} else if (4 == $count) {
$price_1 = $range[0];
$price_2 = $range[1];
$price_3 = $range[2];
$price_4 = $range[3];
$ranges['range1'] = explode(' - ', $price_1);
$ranges['range2'] = explode(' - ', $price_2);
$ranges['range3'] = explode(' - ', $price_3);
$ranges['range4'] = explode(' - ', $price_4);
}
$array = call_user_func_array('array_merge', $ranges);
sort($array);
$min = reset($array);
$max = end($array);
As per my array I want if in array getting single value in array for example
Array
(
[0] => 500 - 1112
[1] => 1113 - 2224
[2] => 2225 - 4446
[3] => 4446
)
So I want to convert this array as shown below,
Array
(
[0] => array(
[0] => 500
[1] => 1112
[2] => 1113
[3] => 2224
[4] => 2225
[5] => 4446
)
[1] => 4446
)
And get min and max from Array ( [0] => array( from this array. Is their any simple way to do.
Thanks in advance
If I correctly understand your example, you provided it with the parameter $count to 2.
So, this could be my version of your request:
The data
<?php
$data[] = '500 - 1112';
$data[] = '1113 - 2224';
$data[] = '4446';
The function
<?php
function explodeRanges(array $data, $counter, $explode = '-') {
$return = [];
// We take the correct number of rows
foreach( array_slice($data, 0, $counter) as $value ) {
$return = array_merge(
$return,
array_map('trim', explode($explode, $value))
);
// trim() function mapped on each elements to clean the data (remove spaces)
// explode all values by the separator
}
return $return;
}
The output
<?php
for( $i = 1 ; $i <= 4 ; $i++ ) {
$range = explodeRanges($data, $i);
echo 'For ', $i, ' => [', implode(', ', $range), ']; MIN = ', min($range), '; MAX = ', max($range);
echo '<hr />';
}
... and the result :)
For 1 => [500, 1112]; MIN = 500; MAX = 1112
For 2 => [500, 1112, 1113, 2224]; MIN = 500; MAX = 2224
For 3 => [500, 1112, 1113, 2224, 4446]; MIN = 500; MAX = 4446
For 4 => [500, 1112, 1113, 2224, 4446]; MIN = 500; MAX = 4446
If you need to repeat your code several times, it's because you can improve it. Here it's quick with a simple function.

how to use round robin method in array in php?

Hi i am trying to create a sub array from an array.i.e; think I have an array such as given below
$array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}
which I explode and assign it to a variable $i..
and run the for loop as shown below..
for ( $i=0;$i<count($array);$i++) {
$a = array();
$b = $array[$i];
for($j=0;$j<count($array);$j++){
if($b != $array[$j]){
$a[] = $array[$j];
}
}
the output I want is when
$i = 1
the array should be
{2,3,4,5,6,7,8,9,10,11}
and when
$i = 2
the array should be
{3,4,5,6,7,8,9,10,11,12}
similarly when
$i=19
the array should be
{1,2,3,4,5,6,7,8,9,10}
so how can I do it.
Assuming $i is supposed to be an offset and not the actual value in the array, you can do
$fullArray = range(1, 19);
$i = 19;
$valuesToReturn = 10;
$subset = iterator_to_array(
new LimitIterator(
new InfiniteIterator(
new ArrayIterator($fullArray)
),
$i,
$valuesToReturn
)
);
print_r($subset);
This will give your desired output, e.g.
$i = 1 will give 2 to 11
$i = 2 will give 3 to 12
…
$i = 10 will give 11 to 1
$i = 11 will give 12 to 2
…
$i = 19 will give 1 to 10
$i = 20 will give the same as $i = 1 again
and so on.
$array = range(1, 19);
$i = 19;
$result = array();
$after = array_slice($array, $i, 10);
$before = array_slice($array, 0, 10 - count($after));
$result = array_merge($after, $before);
var_dump(json_encode($result));
P.S. please note 0 element has 1 value and so on...
for ($i = 0; $i < count($array); $i++) {
if ($i + 10 < count($array))
$a = array_slice($array, $i, 10);
else
$a = array_merge(array_slice($array, $i), array_slice($array, 0, 10-(count($array)-$i)));
// do something with $a before it is over-written on the next iteration
}
This test:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
for ($i = 0; $i < count($array); $i++) {
if ($i + 10 < count($array))
$a = array_slice($array, $i, 10);
else
$a = array_merge(array_slice($array, $i), array_slice($array, 0, 10-(count($array)-$i)));
echo "<h2>$i</h2>\n<pre>".print_r($a,true)."</pre><br />\n";
}
Resulted in this:
0
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
...
9
Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
[5] => 15
[6] => 16
[7] => 17
[8] => 18
[9] => 19
)
10
Array
(
[0] => 11
[1] => 12
[2] => 13
[3] => 14
[4] => 15
[5] => 16
[6] => 17
[7] => 18
[8] => 19
[9] => 1
)
...
18
Array
(
[0] => 19
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
)
This works fine from my end
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
$size = sizeof($array); // Defining the array size
$str = 17; // This is the reference value from which you have to extract the values
$key = array_search($str, $array);
$key = $key+1; // in order to skip the given reference value
$start = $key%$size;
$end = $start+9;
for($i=$start; $i<=$end; $i++) {
$j = ($i%$size);
$result[] = $array[$j];
}
echo '<pre>'; print_r($result);
?>
It looks like all you need is a slice of a certain size from the array, slice that wraps around the array's end and continues from the beginning. It treats the array like a circular list.
You can achieve this in many ways, one of the simplest (in terms of lines of code) is to extend the original array by appending a copy of it at its end and use the PHP function array_slice() to extract the slice you need:
function getWrappedSlice(array $array, $start, $count = 10)
{
return array_slice(array_merge($array, $array), $start, $count);
}
Of course, you have to be sure that $start is between 0 and count($array) - 1 (including), otherwise the value returned by the function won't be what you expect.
Round-robin on an array can be achieved by doing a "rotate" operation inside each iteration:
for ($i = 0; $i < count($array); ++$i) {
// rotate the array (left)
array_push($array, array_shift($array));
// use $array
}
During the loop, the first element of the array is placed at the back. At the end of the loop, the array is restored to its original value.

Getting specidic values from PHP arrays

Is there a way to get the first value from array, then the first value key + 3 ; then +6 then + 9 ans so on
Take this array for example,
array(1,2,5,14,19,2,11,3,141,199,52,24,16)
i want extract a value every 3 so the result would be
array(1,14,11,199,16)
Can i do that with existing PHP array function?
Use a for loop and increment the counter variable by 3.
for ($i = 0; $i <= count(your array); $i+3) {
echo $myarray[i]
}
The following is function that will handle extracting the values from a given array. You can specify the number of steps between each value and if the results should use the same keys as the original. This should work with regular and associative arrays.
<?php
function extractValues($array, $stepBy, $preserveKeys = false)
{
$results = array();
$index = 0;
foreach ($array as $key => $value) {
if ($index++ % $stepBy === 0) {
$results[$key] = $value;
}
}
return $preserveKeys ? $results : array_values($results);
}
$array = array(1, 2, 5, 14, 19, 2, 11, 3, 141, 199, 52, 24, 16);
$assocArray = array('a' => 1, 'b' => 2, 'c' => 5, 'd' => 14, 'e' => 19, 'f' => 2, 11, 3, 141, 199, 52, 24, 16);
print_r(extractValues($array, 3));
print_r(extractValues($array, 3, true));
print_r(extractValues($assocArray, 5));
print_r(extractValues($assocArray, 5, true));
?>
Output
Array
(
[0] => 1
[1] => 14
[2] => 11
[3] => 199
[4] => 16
)
Array
(
[0] => 1
[3] => 14
[6] => 11
[9] => 199
[12] => 16
)
Array
(
[0] => 1
[1] => 2
[2] => 52
)
Array
(
[a] => 1
[f] => 2
[4] => 52
)
Use a loop and check the key.
$result = array();
foreach($array as $key => $value) {
if ($key % 3 === 0) {
$result[] = $value;
}
}
Try below one:
<?php
$your_array = array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$every_3 = array();
$i = 0;
foreach($your_value as $value) {
$i++;
if($i%3==0){
$every_3[]=$value;
}
}
var_dump($every_3);
?>
Do like this
$arr=array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$narr=array();
for($i=0;$i<count($arr);$i=$i+3){
$narr[]=$arr[$i]
}
print_r($narr);
<?php
$mynums = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
foreach ($mynums as $key => $value) {
if ( $key % 3 === 0)
{
$newnum[] = $value;
}
}
var_dump($newnum);
?>
$data = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
$matches = array();
foreach($data as $key => $value)
{
if($key%3 === 0)
{
$matches[] = $value;
}
}
var_dump($matches);
The only way you could do it would be to use a loop, count the length of an array, and loop through using a % mathmatical operator.
It gives you a remainder of a division: http://au2.php.net/operators.arithmetic

Array divide/split by value

$a = array(8, 16, 16, 32, 8, 8, 4, 4);
With an array like the one above is there a way so I can divide/split the array based on the value suming up to a set value. e.g if I wanted them to equal 32. My final array will have upto 100 values all being either 32, 16, 8 or 4 and I just need to group the items so the value always equal a set amount so in this example its 32.
From the above array I would would hope to get:
$a[0][1] = 16
$a[0][2] = 16
$a[1][3] = 32
$a[2][0] = 8
$a[2][4] = 8
$a[2][5] = 8
$a[2][6] = 4
$a[2][7] = 4
as $a[0] sums up to 32 and so does $a[1] and $a[2].
$a = array(8, 16, 16, 32, 8, 8, 4, 4);
$limit = 32;
rsort($a);
$b = array(array());
$index = 0;
foreach($a as $i){
if($i+array_sum($b[$index]) > $limit){
$b[++$index] = array();
}
$b[$index][] = $i;
}
$a = $b;
print_r($a);
It will work, but only because in your case you have 4 | 8 | 16 | 32, and only if the needed sum is a multiple of the biggest number (32).
Test: http://codepad.org/5j5nl3dT
Note: | means divides.
$a = array(8, 16, 16, 32, 8, 8, 4, 4);
$group_limit = 32;
$current_group = $result = array();
$cycles_since_successful_operation = 0;
while ($a && $cycles_since_successful_operation < count($a))
{
array_push($current_group,array_shift($a));
if (array_sum($current_group) > $group_limit)
array_push($a,array_pop($current_group));
elseif (array_sum($current_group) < $group_limit)
$cycles_since_successful_operation = 0;
elseif (array_sum($current_group) == $group_limit)
{
$result []= $current_group;
$current_group = array();
$cycles_since_successful_operation = 0;
}
}
if ($a)
$result []= $a; // Remaining elements form the last group
http://codepad.org/59wmsi4g
function split_into_thirtytwos($input_array) {
$output_array=array();
$work_array=array();
$sum=0;
sort($input_array,SORT_NUMERIC);
while(count($input_array)>0) {
$sum=array_sum($work_array)+$input_array[count($input_array)-1];
if($sum<=32) {
$work_array[]=array_pop($input_array);
} else {
$output_array[]=$work_array;
$work_array=array();
}
}
if(count($work_array)>0) {$output_array[]=$work_array;}
return $output_array;
}
Tested with your input:
Array
(
[0] => Array
(
[0] => 32
)
[1] => Array
(
[0] => 16
[1] => 16
)
[2] => Array
(
[0] => 8
[1] => 8
[2] => 8
[3] => 4
[4] => 4
)
)

Categories