Convert String to custom array PHP - php
i have problem in my function php .
My function php is to check coordinates whether the coordinates are in polygons .
the problem is , i call polygon latlong from database and type data is string and convert to custom array .
this my function
function containsMaps($point1,$value1)
{
$point = preg_split ("/\,/", $point1);
$value = $value1;
foreach(explode('),(',trim($value,'()')) as $single_array){
$sub_array= array();
foreach(explode(',',$single_array) as $sbs_array)
{
$sub_array = array($sbs_array);
}
$polygon = array($sub_array);
}
if($polygon[0] != $polygon[count($polygon)-1])
$polygon[count($polygon)] = $polygon[0];
$j = 0;
$oddNodes = false;
$x = $point[1];
$y = $point[0];
$n = count($polygon);
for ($i = 0; $i < $n; $i++)
{
$j++;
if ($j == $n)
{
$j = 0;
}
if ((($polygon[$i][0] < $y) && ($polygon[$j][0] >= $y)) || (($polygon[$j][0] < $y) && ($polygon[$i][0] >=
$y)))
{
if ($polygon[$i][1] + ($y - $polygon[$i][0]) / ($polygon[$j][0] - $polygon[$i][0]) * ($polygon[$j][1] -
$polygon[$i][1]) < $x)
{
$oddNodes = !$oddNodes;
}
}
}
return $oddNodes;
}
the polygon data from database like this :
(-6.268649975971238, 106.69106266990389),(-6.267711482694832, 106.72625325217928),(-6.288272630052733, 106.72736905112947),(-6.288699201273463, 106.69106266990389)
if i use static data like this , the function working :
$polygon = array(
array(-6.2811957386588855, 106.70141951079609),
array(-6.281142416506361, 106.70432702536823),
array(-6.2781776962328815, 106.70438066954853),
array(-6.2781776962328815, 106.70136586661579),
);
Your code to split the incoming data isn't quite right. This will work:
foreach(explode('),(',trim($value,'()')) as $single_array){
$polygon[] = explode(',',$single_array);
}
Output:
array (
0 =>
array (
0 => '-6.268649975971238',
1 => ' 106.69106266990389',
),
1 =>
array (
0 => '-6.267711482694832',
1 => ' 106.72625325217928',
),
2 =>
array (
0 => '-6.288272630052733',
1 => ' 106.72736905112947',
),
3 =>
array (
0 => '-6.288699201273463',
1 => ' 106.69106266990389',
),
)
Demo on 3v4l.org
Note this will give you string values, if you want floating point values, use code like this:
foreach(explode('),(',trim($value,'()')) as $single_array){
list ($x, $y) = explode(',',$single_array);
$polygon[] = array((double)$x, (double)$y);
}
Demo on 3v4l.org
Related
Finding and removing outliers / anomalies in an array of numbers in PHP
I have an array of numbers like this in PHP: $numbers = [ 0.0021030494216614, 0.0019940179461615, 0.0079320972662613, 0.0040485829959514, 0.0079320972662613, 0.0021030494216614, 0.0019940179461615, 0.0079320972662613, 0.0040485829959514, 0.0079320972662613, 0.0021030494216614, 1.1002979145978, 85.230769230769, 6.5833333333333, 0.015673981191223 ]; In PHP, I am trying to find the outliers / anomalies in this array. As you can see, the anomalies are 1.1002979145978, 85.230769230769, 6.5833333333333, 0.015673981191223 I am trying to find and remove the anomalies in any array. Here is my code function remove_anomalies($dataset, $magnitude = 1) { $count = count($dataset); $mean = array_sum($dataset) / $count; $deviation = sqrt(array_sum(array_map("sd_square", $dataset, array_fill(0, $count, $mean))) / $count) * $magnitude; return array_filter($dataset, function($x) use ($mean, $deviation) { return ($x <= $mean + $deviation && $x >= $mean - $deviation); }); } function sd_square($x, $mean) { return pow($x - $mean, 2); } However, when I put my array of $numbers in, it only gives me [85.230769230769] as the outlier when there are clearly more outliers there. I have tried fiddling with the $magnitude and that did not improve anything.
The algorithm shown here uses mean absolute deviation (MAD) a robust measure to identify outliers. All elements whose distance exceeds a multiple of the MAD are continuously removed and the MAD is recalculated. function median(array $data) { if(($count = count($data)) < 1) return false; sort($data, SORT_NUMERIC); $mid = (int)($count/2); if($count % 2) return $data[$mid]; return ($data[$mid] + $data[$mid-1])/2; } function mad(array $data) { if(($count = count($data)) < 1) return false; $median = median($data); $mad = 0.0; foreach($data as $xi) { $mad += abs($xi - $median); } return $mad/$count; } function cleanMedian(array &$data, $fac = 2.0) { do{ $unsetCount = 0; $median = median($data); $mad = mad($data) * $fac; //remove all with diff > $mad foreach($data as $idx => $val){ if(abs($val - $median) > $mad){ unset($data[$idx]); ++$unsetCount; } } } while($unsetCount > 0); } How to use: $data = [ //.. ]; cleanMedian($data); The parameter $fac needs to be experimented with depending on the data. With the $ fac = 2 you get the desired result. array ( 0 => 0.0021030494216614, 1 => 0.0019940179461615, 2 => 0.0079320972662613, 3 => 0.0040485829959514, 4 => 0.0079320972662613, 5 => 0.0021030494216614, 6 => 0.0019940179461615, 7 => 0.0079320972662613, 8 => 0.0040485829959514, 9 => 0.0079320972662613, 10 => 0.0021030494216614, ) With fac = 4, the value 0.015673981191223 is included.
How can I generate and validate random IDs using the Saudi ID format?
I need to generate random IDs that validate against the criteria for Saudi IDs shown in this question: Saudi Iqama/National Identity number field validation I've tried the following code: $random_numbers = []; while(count($random_numbers) < 1000000000){ do { $random_number = mt_rand(1000000000,9000000000); } while (in_array($random_number, $random_numbers));{ $type = substr ( $random_number, 0, 1 ); if($type != 2 && $type != 1 ) break; $sum = 0; for( $i = 0 ; $i<10 ; $i++ ) { if ( $i % 2 == 0){ $ZFOdd = str_pad ( ( substr($random_number, $i, 1) * 2 ), 2, "0", STR_PAD_LEFT ); $sum += substr ( $ZFOdd, 0, 1 ) + substr ( $ZFOdd, 1, 1 ); }else{ $sum += substr ( $random_number, $i, 1 ); } } return $sum%10 ? break : echo $random_number; ---------- echo "<br>"; $random_numbers[] = $random_number;} }
Disclaimer: I'm not 100% sure on the validation required etc. for Saudi ID numbers and have only briefly looked at the answers supplied in the linked question Okay, so, my understanding is that you need to generate a random id that: Matches the pattern/format: [12]\d{9} Validates against the criteria show in the linked question: Saudi Iqama/National Identity number field validation To do this we need to create a couple of functions; one to generate IDs and one to validate the IDs against the given criteria. Generate the ID Simply generating an ID is simple enough. We can use the random_int function in PHP with a loop. If we enclose the code to generate the ID inside of a do...while... loop then we can execute the code and validate the ID repeatedly until we get a valid one. function getRandomSaudiId() : int { do { $saudiId = (string) random_int(1,2); for($i = 0; $i < 9; $i++){ $saudiId .= random_int(0,9); } } while(validateSaudiId($saudiId) === false); return (int) $saudiId; } Validate the ID Note: we convert to string so that we can access the numbers based on their index. function validateSaudiId(string $id) : bool { $sum = 0; for($i = 0; $i < 9; $i++){ if( $i % 2 ){ // Even number $sum += $id[$i]; } else{ //Odd number $increment = $id[$i] * 2; while($increment > 9){ $increment = (string) $increment; $increment = $increment[0] + $increment[1]; } $sum += $increment; } } $sum = (string) $sum; return ($sum[1] == $id[9] || $id[9] == (10 - $sum[1])) ? true : false; } Example use for($i = 0; $i < 10; $i++) var_dump(getRandomSaudiId()); /* Output: int(2933617506) int(2409806096) int(1072585118) int(2891306413) int(1810304558) int(2591965856) int(1363032527) int(1031823269) int(1265954048) int(2498099472) int(1134172537) */
Get nearest sequence result from an array and given pattern with PHP
I am trying to get year and month from the letters using established sequence. I know that the sequence is based on the following letters: $letters = array('B','C','D','F','G','H','J','K','L','M','N','P','R','S','T','V','W','X','Y','Z'); It started with 0000BBB and when it reaches 9999 it becomes BBC, BBD etc. So I don't need the numbers in that case and only letters as I have a list of last registered sequence per year and month like this: $plates = array( array('2018','KHF','KHX','KJV','KKN','KLM','KML','KNK','KPD','KPR','KPT','----','----'), array('2017','JWN','JXF','JYB','JYT','JZP','KBM','KCH','KCV','KDK','KFB','KFV','KGN'), array('2016','JLN','JMF','JMY','JNR','JPK','JRG','JRZ','JSL','JTB','JTR','JVH','JVZ'), array('2015','JCK','JCY','JDR','JFG','JFW','JGP','JHJ','JHT','JJH','JJW','JKK','JKZ'), array('2014','HVN','HVZ','HWM','HXB','HXN','HYD','HTY','HZB','HZL','HZZ','JBL','JBY'), array('2013','HNT','HPC','HPN','HPY','HRK','HRX','HSK','HSR','HSZ','HTK','HTV','HVF'), array('2012','HJC','HJM','HKB','HKL','HKX','HLK','HLW','HMD','HML','HMT','HNC','HNK'), array('2011','HBP','HCB','HCR','HDC','HDR','HFF','HFT','HGC','HGM','HGX','HHH','HHT'), array('2010','GTC','GTS','GVM','GWC','GWV','GXP','GYD','GYM','GYX','GZJ','GZT','HBG'), array('2009','GKS','GLC','GLP','GMC','GMN','GNF','GNY','GPJ','GPW','GRM','GSC','GSR'), array('2008','FZR','GBN','GCK','GDH','GFC','GFY','GGV','GHG','GHT','GJJ','GJV','GKH'), array('2007','FKY','FLV','FNB','FNZ','FRC','FSJ','FTP','FVJ','FWC','FXB','FXY','FYY'), array('2006','DVW','DWT','DXZ','DYY','FBC','FCJ','FDP','FFK','FGF','FHD','FJD','FKC'), array('2005','DFZ','DGX','DHZ','DKB','DLD','DMJ','DNP','DPK','DRG','DSC','DTB','DVB'), array('2004','CRV','CSS','CTT','CVR','CWR','CXT','CYY','CZP','DBJ','DCH','DDG','DFF'), array('2003','CDV','CFM','CGJ','CHF','CJC','CKB','CLD','CLV','CMM','CNK','CPF','CRC'), array('2002','BSL','BTF','BTZ','BVW','BWT','BXP','BYP','BZF','BZV','CBP','CCH','CDC'), array('2001','BFJ','BGF','BHG','BJC','BKB','BLC','BMF','BMW','BNL','BPG','BRB','BRT'), array('2000','---','---','---','---','---','---','---','---','BBJ','BCD','BCY','BDR') ); That means that array index 0 is the year and from 1 to 12 would be month. I am trying to find a match but then realize I can not search exact value and need to look for nearest value based on letters. I would deeply appreciate if anyone could direct me in right direction what would be the best method of doing this. This is a test so far but this will just return an exact match, I would have to search any possible letters such as KHW as an example that would have to match as nearest value to KHX foreach ($plates as $key => $val) { $search = array_search('KHX', $plates[$key]); if($search){ echo $search."\n"; echo $plates[$key][0]; break; } }
You can solve it with O(log n) with a binary search. But in a more straightforward solution, you can solve it with O(n). You can calculate the difference between each word with the below algorithm. <?php function strToInt($str) { $result = 0; for ($i = 0; $i < strlen($str); $i++) { $result = $result * 100 + ord($str[$i]); } return $result; } function find($searchStr) { $plates = [ ['2018','KHF','KHX','KJV','KKN','KLM','KML','KNK','KPD','KPR','KPT','----','----'], ['2017','JWN','JXF','JYB','JYT','JZP','KBM','KCH','KCV','KDK','KFB','KFV','KGN'], ['2016','JLN','JMF','JMY','JNR','JPK','JRG','JRZ','JSL','JTB','JTR','JVH','JVZ'], ['2015','JCK','JCY','JDR','JFG','JFW','JGP','JHJ','JHT','JJH','JJW','JKK','JKZ'], ['2014','HVN','HVZ','HWM','HXB','HXN','HYD','HTY','HZB','HZL','HZZ','JBL','JBY'], ['2013','HNT','HPC','HPN','HPY','HRK','HRX','HSK','HSR','HSZ','HTK','HTV','HVF'], ['2012','HJC','HJM','HKB','HKL','HKX','HLK','HLW','HMD','HML','HMT','HNC','HNK'], ['2011','HBP','HCB','HCR','HDC','HDR','HFF','HFT','HGC','HGM','HGX','HHH','HHT'], ['2010','GTC','GTS','GVM','GWC','GWV','GXP','GYD','GYM','GYX','GZJ','GZT','HBG'], ['2009','GKS','GLC','GLP','GMC','GMN','GNF','GNY','GPJ','GPW','GRM','GSC','GSR'], ['2008','FZR','GBN','GCK','GDH','GFC','GFY','GGV','GHG','GHT','GJJ','GJV','GKH'], ['2007','FKY','FLV','FNB','FNZ','FRC','FSJ','FTP','FVJ','FWC','FXB','FXY','FYY'], ['2006','DVW','DWT','DXZ','DYY','FBC','FCJ','FDP','FFK','FGF','FHD','FJD','FKC'], ['2005','DFZ','DGX','DHZ','DKB','DLD','DMJ','DNP','DPK','DRG','DSC','DTB','DVB'], ['2004','CRV','CSS','CTT','CVR','CWR','CXT','CYY','CZP','DBJ','DCH','DDG','DFF'], ['2003','CDV','CFM','CGJ','CHF','CJC','CKB','CLD','CLV','CMM','CNK','CPF','CRC'], ['2002','BSL','BTF','BTZ','BVW','BWT','BXP','BYP','BZF','BZV','CBP','CCH','CDC'], ['2001','BFJ','BGF','BHG','BJC','BKB','BLC','BMF','BMW','BNL','BPG','BRB','BRT'], ['2000','---','---','---','---','---','---','---','---','BBJ','BCD','BCY','BDR'] ]; $minYear = null; $minKey = null; $minDiff = strToInt('ZZZ'); $searchInt = strToInt($searchStr); for ($i = 0; $i < count($plates); $i++) { for ($j = 1; $j < 13; $j++) { if(abs($searchInt - strToInt($plates[$i][$j])) < $minDiff) { $minDiff = abs($searchInt - strToInt($plates[$i][$j])); $minYear = $plates[$i][0]; $minKey = $plates[$i][$j]; } } } return [$minYear, $minKey]; } print_r(find('KHW'));
The code down below is by no means optimized, but it's rather a concept of how you might solve your problem. //Flatten out array (one dimension without years and ----) $flatten = array(); foreach($plates as $platevalues) { foreach($platevalues as $pv) { if ($pv != '---' && $pv != '----' && intval($pv) == 0) { //Create a string only if valid letters included in the $letters-array //This string is then added to the new array that is flattened out $pv2 = ''; for($i=0;$i<strlen($pv);$i++) { $letter = substr($pv,$i,1); if (in_array($letter, $letters) !== false) { $pv2 .= $letter; } } $flatten[] = $pv2; } } } //Do the search $search = 'GWN'; $search_result = ''; //Create a new search string based on first found in flattened //plates array (first G, then GW, then GWN) for($i=0;$i<strlen($search);$i++) { foreach($flatten as $key=>$f) { if (substr($search,0,$i+1) == substr($f,0,$i+1)) { $search_result .= substr($search,$i,1); break; } } } /* $search_result is: GW */ //Create a new array where all items that begins with GW are included $result = []; foreach($flatten as $key=>$item) { if (substr($search_result,0,strlen($search_result)) == substr($item,0,strlen($search_result))) { $result[] = $item; } } /* $result = array (size=2) 0 => string 'GWC' (length=3) 1 => string 'GWV' (length=3) */ //Create an array with total ASCII-value for each item //in the $result array above $result_o = []; foreach($result as $item) { $o = 0; for($i=0;$i<strlen($item);$i++) { $o += ord(substr($item,$i,1)); } $result_o[]= $o; } /* $result_o = array (size=2) 0 => int 225 1 => int 244 */ //Get the total ASCII-value for the original search string $search_o = 0; for($i=0;$i<strlen($search);$i++) { $search_o += ord(substr($search,$i,1)); } /* $search_ o = 236 */ //Find closest value in the $result_o (ASCII) - array compared (225,244) //to the original $search_o ASCII value above (236) $closest = 0; $use_key = 0; foreach($result_o as $key=>$item) { if ($closest == 0 || abs($search_o - $closest) > abs($item - $search_o)) { $closest = $item; $use_key = $key; } } /* $closest = 244 (it's closer to 236 than 225 is) $use_key = 1 */ To get the result you have: /* $result = array (size=2) 0 => string 'GWC' (length=3) 1 => string 'GWV' (length=3) */ //This should print out GWV echo 'result=' . $result[$use_key];
PHP A* Pathfinding can't work for complex maze HackerRank
I'm trying to A* pathfinding with Pacman problem using PHP. <?php $_fp = fopen("php://stdin", "r"); // Node class Node { var $x; var $y; var $fCost; var $hCost; var $gCost = 0; var $parent; function __construct($x=0,$y=0){ $this->x = $x; $this->y = $y; } function getNeighbours($depth = 1) { $neighbours = array(); $operand = array( array ('x' => -1, 'y' => 0), array ('x' => 0, 'y' => -1), array ('x' => 0, 'y' => 1), array ('x' => 1, 'y' => 0) ); foreach ($operand as $key => $value) { $checkX = $this->x + $value['x']; $checkY = $this->y + $value['y']; if( $checkX >= 0 && $checkY >= 0 ) array_push( $neighbours, $node = new Node( $checkX, $checkY ) ); } return $neighbours; } function fCost(){ global $food; return $this->gCost() + $this->hCost($food); } function gCost(){ global $pacman; return abs($pacman->x - $this->x) + abs($pacman->y - $this->y); } function hCost($destination){ return abs($destination->x - $this->x) + abs($destination->y - $this->y); } } function retracePath($start,$end) { $current = $end; while ( $current != $start ) { echo $current->x . " " . $current->y."<br>"; $current = $current->parent; } } $pacman = new Node(); $food = new Node(); // Input data fscanf($_fp, "%d %d", $pacman->x, $pacman->y); // Pacman's position fscanf($_fp, "%d %d", $food->x, $food->y); // Food's position fscanf($_fp, "%d %d", $row_size, $col_size); // For map size row and col // Input for map by row for($row=0; $row<$row_size; $row++) { $map[$row] = trim(fgets(STDIN)); } // Astar $arr_open = array(); // set of nodes to be evaluated $arr_close = array(); // set of nodes already evaluated array_push($arr_open, $pacman); // add the start node to $arr_open $key_arr_open = 0; while( count($arr_open) > 0 ) { // loop $current = new Node(); $current = $arr_open[$key_arr_open]; unset($arr_open[$key_arr_open]); array_push($arr_close, $current); if($current->x == $food->x && $current->y == $food->y) { retracePath($pacman,$current); echo "sukses<br>" break; } $neighbours = $current->getNeighbours(); foreach ($neighbours as $key => $data) { if($map[$data->x][$data->y] == "%" or in_array($data, $arr_close)) { //echo "not traversable<br>"; continue; } $new_cost_to_neighbour = $current->gCost() + $current->hCost($data); if( $new_cost_to_neighbour < $data->gCost() or !in_array( $data, $arr_open ) ) { $data->gCost = $new_cost_to_neighbour; $data->hCost = $data->hCost($food); $data->fCost = $new_cost_to_neighbour + $data->hCost($food); $data->parent = $current; if( !in_array($data, $arr_open) ) { array_push($arr_open, $data); } } } $key_arr_open ++; } ?> Input format : Position x and y pacman, position x and y food, count row and column of tile, then the grid. Grid format is "P" for pacman, "." for food, "-" for traversable path and "%" for wall. The problem is when I give input with 6x6 tile like this : %%%%%% %-%%-% %-%%-% %-%%-% %.--P% %%%%%% The code is work. But, if I give input with 37x37 tile with complex maze, the node in the array of open always looped. (From HackerRank) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %-------%-%-%-----------%---%-----%-% %-%%%%%%%-%-%%%-%-%%%-%%%-%%%%%%%-%-% %-------%-------%-%-----%-----%-%---% %%%%%-%%%%%-%%%-%-%-%-%%%-%%%%%-%-%%% %---%-%-%-%---%-%-%-%---%-%---%-%---% %-%%%-%-%-%-%%%-%%%%%-%%%-%-%%%-%%%-% %-------%-----%---%---%-----%-%-%---% %%%-%%%%%%%%%-%%%%%%%-%%%-%%%-%-%-%-% %-------------%-------%-%---%-----%-% %-%-%%%%%-%-%%%-%-%-%%%-%-%%%-%%%-%-% %-%-%-----%-%-%-%-%-----%---%-%-%-%-% %-%-%-%%%%%%%-%-%%%%%%%%%-%%%-%-%%%-% %-%-%-%-----%---%-----%-----%---%---% %%%-%%%-%-%%%%%-%%%%%-%%%-%%%-%%%%%-% %-----%-%-%-----%-%-----%-%---%-%-%-% %-%-%-%-%-%%%-%%%-%%%-%%%-%-%-%-%-%-% %-%-%-%-%-----------------%-%-%-----% %%%-%%%%%%%-%-%-%%%%%-%%%-%-%%%-%%%%% %-------%-%-%-%-----%---%-----%-%---% %%%%%-%-%-%%%%%%%%%-%%%%%%%%%%%-%-%%% %---%-%-----------%-%-----%---%-%---% %-%%%-%%%%%-%%%%%%%%%-%%%%%-%-%-%%%-% %-%---%------%--------%-----%-------% %-%-%-%%%%%-%%%-%-%-%-%-%%%%%%%%%%%%% %-%-%---%-----%-%-%-%-------%---%-%-% %-%-%%%-%%%-%-%-%-%%%%%%%%%-%%%-%-%-% %-%---%-%---%-%-%---%-%---%-%-%-----% %-%%%-%%%-%%%%%-%%%-%-%-%%%%%-%-%%%%% %-------%---%-----%-%-----%---%-%---% %%%-%-%%%%%-%%%%%-%%%-%%%-%-%%%-%-%%% %-%-%-%-%-%-%-%-----%-%---%-%---%-%-% %-%-%%%-%-%-%-%-%%%%%%%%%-%-%-%-%-%-% %---%---%---%-----------------%-----% %-%-%-%-%%%-%%%-%%%%%%%-%%%-%%%-%%%-% %.%-%-%-------%---%-------%---%-%--P% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Your program is almost correct. The problem arises from using in_array() for looking up a node in $arr_close or $arr_open, because in_array() compares not only the position $x, $y, but also the other Node members $fCost, $hCost, $gCost ...; thus it doesn't recognize that a node is already in the closed set of nodes already evaluated if those other members differ, and gets to evaluate it repeatedly. A quick fix is to use instead of in_array() a self-defined function that as needed only compares the $x, $y members: function in($node, $arr) { foreach ($arr as &$member) if ($member->x == $node->x && $member->y == $node->y) return TRUE; return FALSE; }
PHP How can I get HEX Color code from array of R + G + B?
I have an array: Array ( [red] => 252 [green] => 168 [blue] => 166 [alpha] => 0 ) It's an output of function imagecolorsforindex. How can I get a HTML code from these elements? For example: #99CCFF
Strictly speaking you can't, since alpha is not supported. But since the alpha is 0, we can assume that it won't matter. As such, pass each value into sprintf() with a format specifier of %02x for each element. c = sprintf('#%02x%02x%02x', val['red'], val['green'], val['blue']);
PHP Convert RGB from/to HTML hex color rgb2html($array[0], $array[1], $array[2])
There's a function contributed in the comments of this page of the PHP manual. <?PHP function rgb2hex2rgb($c){ if(!$c) return false; $c = trim($c); $out = false; if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){ $c = str_replace('#','', $c); $l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false); if($l){ unset($out); $out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l)); $out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l)); $out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l)); }else $out = false; }elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){ $spr = str_replace(array(',',' ','.'), ':', $c); $e = explode(":", $spr); if(count($e) != 3) return false; $out = '#'; for($i = 0; $i<3; $i++) $e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i])); for($i = 0; $i<3; $i++) $out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i]; $out = strtoupper($out); }else $out = false; return $out; } ?> Output #FFFFFF => Array{ red=>255, green=>255, blue=>255, r=>255, g=>255, b=>255, 0=>255, 1=>255, 2=>255 } #FFCCEE => Array{ red=>255, green=>204, blue=>238, r=>255, g=>204, b=>238, 0=>255, 1=>204, 2=>238 } CC22FF => Array{ red=>204, green=>34, blue=>255, r=>204, g=>34, b=>255, 0=>204, 1=>34, 2=>255 } 0 65 255 => #0041FF 255.150.3 => #FF9603 100,100,250 => #6464FA
You can try this simple piece of code below. $rgb = (123,222,132); $rgbarr = explode(",",$rgb,3); echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]); This will return #7bde84