Convert string in MySQL table field to array in PHP - php

Problem:
I have a field in my MySQL table with the following value:
9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 28, 29, 30, 31, 32
I use PHP to put the value of this field in the variable: $row['Exclude'];
The problem is that I am using a function called rand_except() that looks as following:
function rand_except($min, $max, $except)
{
//first sort array values
sort($except, SORT_NUMERIC);
//calculate average gap between except-values
$except_count = count($except);
$avg_gap = ($max - $min + 1 - $except_count) / ($except_count + 1);
if ($avg_gap <= 0)
return false;
//now add min and max to $except, so all gaps between $except-values can be calculated
array_unshift($except, $min - 1);
array_push($except, $max + 1);
$except_count += 2;
//iterate through all values of except. If gap between 2 values is higher than average gap,
// create random in this gap
for ($i = 1; $i < $except_count; $i++)
if ($except[$i] - $except[$i - 1] - 1 >= $avg_gap)
return mt_rand($except[$i - 1] + 1, $except[$i] - 1);
return false;
}
In order for this to work it needs to be like this:
$exclude = array(9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 28, 29, 30, 31, 32);
$_SESSION['experimentversion'] = rand_except(1, 32, $exclude);
Question:
How can I take the database field $row['Exclude'] and transform it into an array so it will work with the function?

Simple. Use Explode function.
$s = "1,2,3,4";
$y = explode(",", $s);
print_r($y)

There is a explode method in php you can use this method
$string = '1,2,3,4,5';
$array = explode(",",$string);
print_r($array);
it will create an array.

$exclude = explode(', ', $row['Exclude']);

$str = '1,2,3,4,5';
$arr = explode(",",$str);
print_r($arr);

This should do the trick:
$exclude = explode(", ", $row['Exclude']);

use explode function.. for more info of Explode Visi this link
$row = "retrive your value from db";
$data = explode(", ",$row);
print_r($data); //here you will get array of your db field

Related

To sum elements of array between a range of index, what would be best way to do it in PHP?

Lets say for $numArr = array(10,20,30,40,50,60,70,80,90,100);
how to sum between specific range like 30 - 60 to get sum of 180.. (30+40+50+60).
edit : This is my latest code
<?php
function sum_array ($no1, $no2){
$array = array(10,20,30,40,50,60,70,80,90,100);
$input = array_slice($array, $no1, $no2);
return array_sum($input);
}
echo sum_array(0,3);
?>
I made a basic function for this according to u guys replies .. though still i want to put some validations into this like the parameters should be positive else the function should return -1 .. and what if the second index of the range is not in array.. like (90-120). Would it able to still sum what's in range and in array .. and give 190 to the above range.
$numArr = [ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ];
$startValue = 30;
$endValue = 60;
$startIndex = array_search($startValue, $numArr);
$endIndex = array_search($endValue, $numArr);
$length = $endIndex - $startIndex + 1;
$result = array_sum(array_slice($numArr, $startIndex, $length));
print_r($result);

PHP array slice from position + attempt to return fixed number of items

I'm looking for an efficient function to achieve the following. Let's say we have an array:
$a = [0, 1, 2, 3, 4, 5, 6, 7];
Slicing from a position should always return 5 values. 2 before the position index and 2 values after the position index - and of course, the position index itself.
If a position index is at the beginning of the array i.e. 0 (example 2), the function should return the next 4 values. Similarly, if the position index is at the end of the array (example 3), the function should return the previous 4 values.
Here's some examples of various indexes one could pass to the function and expected results:
$index = 3; // Result: 1, 2, 3, 4, 5. *example 1
$index = 0; // Result: 0, 1, 2, 3, 4. *example 2
$index = 7; // Result: 3, 4, 5, 6, 7. *example 3
$index = 6; // Result: 3, 4, 5, 6, 7. *example 4
As represented in examples: (example 1, example 4), the function should always attempt to catch tokens succeeding and preceding the position index - where it can, whilst always returning a total of 5 values.
The function must be bulletproof to smaller arrays: i.e if $a has 4 values, instead of 5, the function should just return everything.
Something like this?
#edit:
Sorry, I misread your original requirement. Second attempt:
function get_slice_of_5($index, $a) {
if ($index+2 >= count($a)) {
return array_slice($a, -5, 5)
}
else if($index-2 <= 0) {
return array_slice($a, 0, 5)
}
else return array_slice($a, $index-2, 5)
}
Create a start position by calculating where to start and use implode and array slice to return the string.
$a = [0, 1, 2, 3, 4, 5, 6, 7];
$index = 3; // Result: 1, 2, 3, 4, 5. *example 1
echo pages($a, $index) . "\n";
function pages($a, $index){
if($index >= count($a)-2){
$start = count($a)-5; // index is at end of array
}elseif($index <=2){
$start = 0; // index is at start
}else{
$start = $index-2; // index is somewhere in the middle
}
return implode(", ", array_slice($a, $start, 5));
}
https://3v4l.org/aNZsB
this is a "standalone" function to get spliced arrays of any size:
$a = [1,2,3,4,5,6,7,8,9];
echo "<pre>"; print_r(array_slicer($a, 2));
function array_slicer($arr, $start){
// initializations
$arr_len = count($arr);
$min_arr_len = 5; // the size of the spliced array
$previous_elements = 2; // number of elements to be selected before the $start
$next_elements = 2; // number of elements to be selected after the $start
$result = [];
// if the $start index doesn't exist in the given array, return false!
if($start<0 || $start>=$arr_len){
return false;
} elseif($arr_len <= $min_arr_len){ // if the size of the given array is less than the d size of the spliced array, return the whole array!
return $arr;
}
// check if the $start has less than ($previous_elements) before it
if($arr_len - ($arr_len - $start) < $previous_elements){
$next_elements += ($next_elements - ($arr_len - ($arr_len - $start)));
} elseif(($arr_len - 1 - $start) < $next_elements){ // check if the $start has less than ($next_elements) after it
$previous_elements += ($previous_elements - ($arr_len - 1 - $start));
}
for($i = ($start-$previous_elements); $i <= ($start + $next_elements); $i++){
if($i>-1 && $i<$arr_len){
$result[] = $arr[$i];
}
}
return $result;
}
You can define the bounds of where the array_slice() will begin by leveraging min() and max(). Assuming your array will always have at least 5 element, you can use:
array_slice($a, min(count($a) - 5, max(0, $index - 2)), 5)
The chosen index will be in the center of the sliced array unless it cannot be.
Dynamic Code: (Demo)
$a = [0, 1, 2, 3, 4, 5, 6, 7];
$count = count($a);
$span = 5; // most sensible with odd numbers
$center = (int)($span / 2);
foreach ($a as $i => $v) {
printf(
"%d: %s\n",
$i,
implode(
',',
array_slice(
$a,
min($count - $span, max(0, $i - $center)),
$span
)
)
);
}
Output:
0: 0,1,2,3,4
1: 0,1,2,3,4
2: 0,1,2,3,4
3: 1,2,3,4,5
4: 2,3,4,5,6
5: 3,4,5,6,7
6: 3,4,5,6,7
7: 3,4,5,6,7

Summing only positive numbers in PHP array

First of all, thanks for looking at my question.
I only want to add up the positive numbers in the $numbers using a if,else statement.
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
if ($numbers < 0 {
$numbers = 0;
}
elseif (now i want only the positive numbers to add up in the $total.)
I'm an first years student and I am trying to understand the logic.
I'm not gonna give the direct answer, but the way here is you need a simple loop, can be for or a foreach loop, so every iteration you just need to check whether the current number in the loop is grater than zero.
Example:
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
foreach($numbers as $number) { // each loop, this `$number` will hold each number inside that array
if($number > 0) { // if its greater than zero, then make the arithmetic here inside the if block
// add them up here
// $total
} else {
// so if the number is less than zero, it will go to this block
}
}
Or as michael said in the comments, a function also can be used in this purpose:
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = array_sum(array_filter($numbers, function ($num){
return $num > 0;
}));
echo $total;
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
foreach($numbers as $number)
{
if($number > 0)
$total += $number;
}
this loops through all elements of the array(foreach = for each number in the array) and checks if the element is bigger than 0, if it is, add it to the $total

lotto.php (I'm struggling with random numbers into "ticket")

I'm lost. I'm struggling with random numbers for my lotto.php. The first is going to my HTML:
<textarea name="ticket" rows="20" cols="20"></textarea>
How to take "ticket" to standard php format?
// Set the min/max
$numbers = array_fill(1,47,0);
// array-slice
$numbers = range(1, 47);
shuffle($numbers);
$numbers = array_slice($numbers, 0, 6);
print_r($numbers);
Also, I must have $_POST too.
Make use of implode() of PHP
<?php
$numbers = array_fill(1,47,0);
// array-slice
$numbers = range(1, 47);
shuffle($numbers);
$numbers = array_slice($numbers, 0, 6);
//print_r($numbers);
$lottonum = implode(" ", $numbers); // Space as seperator
echo $lottonum;
OUTPUT :
45 24 6 25 17 28

converting string to integer value

having the string
010100
Nowing that this is in hex. How would you obtain the resulting values of:
id = 4;
part = 1;
setting = 0;
increment=0;
Knowing that in this string id should be a 10 bit value, part a 6 bit value, setting a 2 bit value, increment with 6 bits how would you generate the string ?
Thank you for any help.
SORRY, missed the value increment for this to make more sense...
You could do something like:
// 123456789012345612123456
$str = '000001010110000111000111';
// 21 33 3 7
$id = base_convert(substr($str, 0, 10), 2, 10);
$part = base_convert(substr($str, 10, 6), 2, 10);
$setting = base_convert(substr($str, 16, 2), 2, 10);
$increment = base_convert(substr($str, 18, 6), 2, 10);
echo "id = $id\npart = $part\nsetting = $setting\nincrement = $increment\n";
Output:
id = 21
part = 33
setting = 3
increment = 7

Categories