fill a series of numbers seperated by dash or comma - php

I need to fill series of numbers where dash or comma is in use.
I'm using this code that works fine but when numbers starts with zero it's not working (the leading zero drop)
$str = str_replace(' ', '', '11-17,19,041244-041250);
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
for($i = $values[0]; $i <= $values[1]; $i++) {
$newArr[]=$i;
}
} else {
$newArr[] = $elem;
}
print_r($newArr);
}
Any help will be appreciated

Try this. Taken from here: Incrementing numbers starting from 0000 in php
<?php
$str = str_replace(' ', '', '11-17,19,041244-041250');
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
for($i = $values[0]; $i <= $values[1]; $i++) {
//$newArr[]=$values[0]++;
$newArr[] = str_pad($i + 1, strlen($values[0]), 0, STR_PAD_LEFT);
}
} else {
$newArr[] = $elem;
}
print_r($newArr);
}

This line:
for($i=$values[0];$i<=$values[1];$i++) $newArr[]=$i;
Is the reason this is happening. What you are doing wrong is feeding the initial loop value as a string. You can cast it to an integer and it should fix your problem.
i.e:
for($i=(int)$values[0];$i<=(int)$values[1];$i++) $newArr[]=$i;
Another approach you could consider would be:
$newArr = array_merge($newArr, range((int)$values[0],(int)$values[1]));
Just make sure to initiate $newArr = []; prior to using that method.
Look into: http://php.net/manual/en/function.range.php

<?php
$str = str_replace(' ', '', '11-17,19,041244-041250');
$arr = explode(',', $str);
foreach ($arr as $elem) {
$values = explode('-',$elem);
if (count($values) != 1) {
$newArr[] = $values[0];
for($i = $values[0]; $i < $values[1]; $i++) {
$newArr[] = str_pad($i + 1, strlen($values[0]), 0, STR_PAD_LEFT);
}
}else{
$newArr[] = $elem;
}
}
print_r($newArr);
}

Related

PHP string expansion

I have a string composed by many letters, at some point, one letter from a group can be used and this is represented by letters enclosed in []. I need to expand these letters into its actual strings.
From this:
$str = 'ABCCDF[GH]IJJ[KLM]'
To this:
$sub[0] = 'ABCCDFGIJJK';
$sub[1] = 'ABCCDFHIJJK';
$sub[2] = 'ABCCDFGIJJL';
$sub[3] = 'ABCCDFHIJJL';
$sub[4] = 'ABCCDFGIJJM';
$sub[5] = 'ABCCDFHIJJM';
UPDATE:
Thanks to #Barmar for the very valuable suggestions.
My final solution is:
$str = '[GH]DF[IK]TF[ADF]';
function parseString(string $str) : array
{
$i = 0;
$is_group = false;
$sub = array();
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
foreach ($chars as $key => $value)
{
if(ctype_alpha($value))
{
if($is_group){
$sub[$i][] = $value;
} else {
if(!isset($sub[$i][0])){
$sub[$i][0] = $value;
} else {
$sub[$i][0] .= $value;
}
}
} else {
$is_group = !$is_group;
++$i;
}
}
return $sub;
}
The recommended function for combinations is (check the related post):
function array_cartesian_product($arrays)
{
$result = array();
$arrays = array_values($arrays);
$sizeIn = sizeof($arrays);
$size = $sizeIn > 0 ? 1 : 0;
foreach ($arrays as $array)
$size = $size * sizeof($array);
for ($i = 0; $i < $size; $i++) {
$result[$i] = array();
for ($j = 0; $j < $sizeIn; $j++)
array_push($result[$i], current($arrays[$j]));
for ($j = ($sizeIn - 1); $j >= 0; $j--) {
if (next($arrays[$j]))
break;
elseif (isset($arrays[$j]))
reset($arrays[$j]);
}
}
return $result;
}
Check the solution with:
$combinations = array_cartesian_product(parseString($str));
$sub = array_map('implode', $combinations);
var_dump($sub);
Convert your string into a 2-dimensional array. The parts outside brackets become single-element arrays, while each bracketed trings becomes an array of single characters. So your string would become:
$array =
array(array('ABCCDF'),
array('G', 'H', 'I'),
array('IJJ'),
array('K', 'L', 'M'));
Then you just need to compute all the combinations of those arrays; use one of the answers at How to generate in PHP all combinations of items in multiple arrays. Finally, you concatenate each of the resulting arrays with implode to get an array of strings.
$combinations = combinations($array);
$sub = array_map('implode', $combinations);

How should merge 2 element of array in PHP?

I want to merge 2 element in array in PHP how can i do that. Please any on tell me.
$arr = array('Hello','World!','Beautiful','Day!'); // these is my input
//i want output like
array('Hello World!','Beautiful Day!');
The generic solution would be something like this:
$result = array_map(function($pair) {
return join(' ', $pair);
}, array_chunk($arr, 2));
It joins together words in pairs, so 1st and 2nd, 3rd and 4th, etc.
Specific to that case, it'd be very simple:
$result = array($arr[0].' '.$arr[1], $arr[2].' '.$arr[3]);
A more general approach would be
$result = array();
for ($i = 0; $i < count($arr); $i += 2) {
if (isset($arr[$i+1])) {
$result[] = $arr[$i] . ' ' . $arr[$i+1];
}
else {
$result[] = $arr[$i];
}
}
In case your array is not fixed to 4 elements
$arr = array();
$i = 0;
foreach($array as $v){
if (($i++) % 2==0)
$arr[]=$v.' ';
else {
$arr[count($arr)-1].=$v;
}
}
Live: http://ideone.com/VUixMS
Presuming you dont know the total number of elements, but do know they will always an even number (else you cant join the last element), you can simply iterate $arr in steps of 2:
$count = count($arr);
$out=[];
for($i=0; $i<$count; $i+=2;){
$out[] = $arr[$i] . ' ' .$arr[$i+1];
}
var_dump($out);
Here it is:
$arr = array('Hello', 'World!', 'Beautiful', 'Day!');
$result = array();
foreach ($arr as $key => $value) {
if (($key % 2 == 0) && (isset($arr[$key + 1]))) {
$result[] = $value . " " . $arr[$key + 1];
}
}
print_r($result);
A easy solution would be:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);

Determine repeat characters in a php string

I have found many examples of how to find repeat characters in a string. I believe my requirement is unique.
I have string
$string=aabbbccddd;
I need to determine which character was repeated the most.
So for the above example it would say
The character repeated the most is "B".
However in the example above both B and D are repeated 3 times.
Would need to spot that. B AND D are both repeated 3 times.
This is what I have so far. FAR from what I need but starting point
<?php
$string = "aabbbccddd";
$array=array($array);
foreach (count_chars($string, 1) as $i => $val) {
$count=chr($i);
$array[]= $val.",".$count;
}
print_r($array);
?>
Anyone have any thing that could help me?
Based on georg's great point, I would use a regex. This will handle split duplicates like ddaaddd with array keys dd=>2 and ddd=>3 but will only show one entry for dd when given ddaadd. To represent both would require a more complex array:
$string = "ddaabbbccddda";
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[0], array_map('strlen', $matches[0]));
arsort($result);
If you only need a count of ALL occurrences try:
$result = array_count_values(str_split($string));
arsort($result);
Legacy Answers:
If you don't have split duplicates:
$string = 'aabbbccddd';
$letters = str_split($string);
$result = array_fill_keys($letters, 1);
$previous = '';
foreach($letters as $letter) {
if($letter == $previous) {
$result[$letter]++;
}
$previous = $letter;
}
arsort($result);
print_r($result);
Or for a regex approach:
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[1], array_map('strlen', $matches[0]));
arsort($result);
Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);
use count-chars()
http://php.net/manual/en/function.count-chars.php
and then asort()
http://php.net/manual/en/function.asort.php
<?php
$word = "abcdefghbi";
for($i=0; $i<strlen($word);$i++){
for($k=0;$k<strlen($word);$k++){
if($word[$i] == $word[$k] && $i != $k){
echo $word[$k]." is duplicate";
exit;
}
}
}
echo "no match found";
?>
$data = "aabbbcccdddz";
$array = str_split($data);
$v = array_count_values($array);
foreach($v as $k => $val){
echo $k.' = '.$val.'<br>';
}

PHP implode() using conditional logic based on object index

Assuming a list like this:
$array = array('item1', 'item2', 'item3'); // etc...
I would like to create a comma separated list like so:
implode(',', $array);
But have the added complication that I'd like to use the following logic: if the item index is a multiple of 10, use ',<br>' instead of just ',' for the separator in the implode() function.
What's the best way to do this with PHP?
I did this like so, but wonder if there's a more concise way?
function getInventory($array, $title) {
$list = array();
$length = count($array);
$i = 1;
foreach($array as $item) {
$quantity = $item[1];
if(!$quantity)
$quantity = 1;
$item_text = $quantity . $item[3];
if($i > 9 && ($i % 10) == 0) {
$item_text .= ',<br>';
} elseif($i !== $length) {
$item_text .= ',';
}
$list[] = $item_text;
$i++;
}
$list = implode('', $list);
$inventory = $title . $list . '<br>';
return $inventory;
}
This solution will work if you want to use the <br> whenever the key is divisible by 10.
implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, array_keys($array)));
If instead you want every 10th element and not just the element where the key is divisible by 10, use this:
implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, range(1, count($array)));
Thanks to #Jacob for this possibility.
We keep the , for the implode function and variably adjust the input array values to be prepended with a <br>.
$k%10 uses the modulus operator to return the remainder for $k divided by 10 which will be 0 when $k is a multiple of 10.
As long as it's not the actual array keys that you're concerned about but the position in the array (ie. the break is on every tenth element rather than every index that is a multiple of ten), then you can do it this way:
$foo = array();
for($n = 0; $n < 54; $n++) $foo[] = $n;
$parts = array_chunk($foo, 10);
for($n = 0; $n < count($parts); $n++){
echo implode(',', $parts[$n]);
if($n < count($parts) - 1) echo ',';
echo "<br/>\n";
}
$str = '';
$array = ....;
$i = 0;
foreach($array as $index)
$str .= $array[$index].' ,'.($index % 10 ? ' ' : '<br/>');
$str = substr($str, 0, strlen($str) - 2); // trim the last two characters ', '

How to convert every two consecutive values of an array into a key/value pair?

I have an array like the following:
array('category_name:', 'c1', 'types:', 't1')
I want the alternate values of an array to be the values of an array:
array('category_name:' => 'c1', 'types:' => 't1')
You could try: (untested)
$data = Array("category_name:","c1","types:","t1"); //your data goes here
for($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) {
$key = $data[$i];
$value = $data[$i+1];
$output[$key] = $value;
}
Alternatively: (untested)
$output = Array();
foreach($data as $key => $value):
if($key % 2 > 0) { //every second item
$index = $data[$key-1];
$output[$index] = $value;
}
endforeach;
function fold($a) {
return $a
? array(array_shift($a) => array_shift($a))
+ fold($a)
: array();
}
print_r(fold(range('a','p' )));
~)
upd: a real-life version
function fold2($a) {
$r = array();
for($n = 1; $n < count($a); $n += 2)
$r[$a[$n - 1]] = $a[$n];
return $r;
}
Here is another yet complex solution:
$keys = array_intersect_key($arr, array_flip(range(0, count($arr)-1, 2)));
$values = array_intersect_key($arr, array_flip(range(1, count($arr)-1, 2)));
$arr = array_combine($keys, $values);
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];

Categories