I have an array variable $arr = array('A','B','C','D');
$number = 5; (This is dynamic)
My new array value should be
$arr = array('A','B','C','D','E','F','G','H','I');
If
$number = 3;
Output should be:
$arr = array('A','B','C','D','E','F','G');
If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.
How to do that in PHP code?
How about this one: https://3v4l.org/IGhoL
<?php
/**
* Increments letter
* #param int $number
* #param array &$arr
*/
function increment($number, &$arr) {
$char = end($arr);
$char++;
for ($i = 0; $i < $number; $i++, $char++) {
$arr[] = $char;
}
}
$arr = range('A', 'D');
$number = 30;
increment($number, $arr);
var_dump($arr);
You can increment letters by incrementing it, then store it that array itself. This will print two letter sequence also ie., AA, AB ...
$arr = array('A','B','C','D');
$item = end($arr) ;
$i = 0 ;
while( $i++ < $number ) {
$arr[] = ++$item ;
}
print_r($arr) ;
Here is example to add chars from alphabet to array with offset. This works for one char. If you wish to work for more chars use loop in loop.
for ($c = ord('A') + $offset ;$c <= ord('Z');$c++) {
Array[] += chr($c);
}
$output = array();
$arr = array(A,B,C,D,E);
$data = range('F','Z');
$num = 4;
if($num < 22){
$output = array_merge($arr,array_slice($data, 0, $num));
}else{
// Write ur format here..
// $output = array('AA','AB',......,'AZ');
}
echo '<pre>';
print_r($output);
Related
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);
i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>
This is my code but it only gives results if both strings are of same length. But what if I want to compare strings of different lengths?
<?php
$n1 = "Apple";
$n2 = "Orang";
//count length fo both string
$count1 = strlen($n1);
$count2 = strlen($n2);
$finalcount = 0;
if($count1 > $count2) {
$finalcount = $count1;
} elseif ($count1 < $count2) {
$finalcount = $count2;
} else {
$finalcount = $count1;
}
//convert string to array
$n1 = str_split($n1);
$n2 = str_split($n2);
$i = 0;
$result = "";
for($i = 0;$i < $finalcount ; $i++) {
$result = $result .$n1[$i] . $n2[$i];
}
echo $result;
?>
This would be one way to do it (some explanation in the comments):
<?php
$str = 'test';
$str2 = 'test2';
$arr = str_split($str);
$arr2 = str_split($str2);
// Find the longest string
$max = max(array(strlen($str), strlen($str2)));
$result = '';
for($i = 0; $i < $max; $i++){
// Check if array key exists. If so, add it to result
if (array_key_exists($i, $arr)){
$result .= $arr[$i];
}
if (array_key_exists($i, $arr2)){
$result .= $arr2[$i];
}
}
echo $result; //tteesstt2
?>
Here is exactly what you are looking for:
PHP - Merge two strings
/**
* Merges two strings in a way that a pattern like ABABAB will be
* the result.
*
* #param string $str1 String A
* #param string $str2 String B
* #return string Merged string
*/
function MergeBetween($str1, $str2){
// Split both strings
$str1 = str_split($str1, 1);
$str2 = str_split($str2, 1);
// Swap variables if string 1 is larger than string 2
if (count($str1) >= count($str2))
list($str1, $str2) = array($str2, $str1);
// Append the shorter string to the longer string
for($x=0; $x < count($str1); $x++)
$str2[$x] .= $str1[$x];
return implode('', $str2);
}
<?php
// Write a program to concatenate two strings character by
// character. e.g : JOHN + SMITH = JSOMHINTH
echo "\nstring 1 : ".$string1="JOHN";
echo "\nstring 2 : ".$string2="SMITH";
$firstArray=str_split($string1);
$secondArray=str_split($string2);
if(count($firstArray)>count($secondArray)) {
$loop=count($firstArray);
}
else {
$loop=count($secondArray);
}
$result=[];
$i=0;
while($i<$loop) {
isset($firstArray[$i])?array_push($result,$firstArray[$i]):'';
isset($secondArray[$i])?array_push($result,$secondArray[$i]):'';
$i++;
}
echo "\nResult String : ".implode($result);
?>
I have a code in PHP that is able to generate a 6-character alpha-numeric string but it does not ensure that there are 3 letters and 3 numbers generated.
It generates a string such as "ps7ycn"
It does not have 3 numbers in between the alphabet.
The numbers should be in between the letters.
example : a3g5h9
This will ensure you only get alternating letters and numbers:
Code: (Demo)
$letters='abcdefghijklmnopqrstuvwxyz'; // selection of a-z
$string=''; // declare empty string
for($x=0; $x<3; ++$x){ // loop three times
$string.=$letters[rand(0,25)].rand(0,9); // concatenate one letter then one number
}
echo $string;
Potential Outputs:
i9f6q0
j4u5p4
j6l6n9
p.s. If you want to randomize whether the first character is a letter or number, use this line of code after the for loop.
if(rand(0,1)){$string=strrev($string);}
rand() will generate a 0 or a 1, the conditional will treat 0 as false and 1 as true. This offers a "coin flip" scenario regarding whether to reverse the string or not.
If you want to guarantee unique letters and numbers in the output...
$letters=range('a','z'); // ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
shuffle($letters);
$numbers=range(0,9); // [0,1,2,3,4,5,6,7,8,9]
shuffle($numbers);
$string='';
for($x=0; $x<3; ++$x){
$string.=$letters[$x].$numbers[$x];
}
echo $string;
Try this code:
$str = '';
for ( $i = 1; $i <= 6; ++$i ) {
if ( $i % 2 ) {
$str .= chr(rand(97,122));
}else{
$str .= rand(0,9);
}
}
This one is shorter but you can not use it to have odd length like a1g7y5k :
$str = '';
for ( $i = 1; $i <= 3; ++$i ) {
$str .= chr(rand(97,122)) . rand(0,9);
}
-Alternatively use this method that can be improved ( refer to mickmackusa's comments):
$alphas = 'abcdefghijklmnopqrstuvwxyz';
$numbers = '0123456789';
$arr1 = str_split($alphas);
$arr2 = str_split($numbers);
$arr3 = array_rand($arr1,3);
$arr4 = array_rand($arr2,3);
$arr5 = array();
for ($i=0; $i<count($arr3); $i++) {
$arr5[] = $arr3[$i];
$arr5[] = $arr4[$i];
}
$result = implode('',$arr5);
Check this thread.It has some good ideas and functions.
Here's one way you could address this:
$alpha = 'abcdefghijklmnopqrstuvwxyz';
$number = '0123456789';
$random = '';
for ( $i = 0; $i < 6; ++$i ) {
if ( $i % 2 ) {
$random .= substr( $number, rand( 0, strlen( $number ) - 1 ), 1 );
} else {
$random .= substr( $alpha, rand( 0, strlen( $alpha ) - 1 ), 1 );
}
}
$random will now contain a six-character random value with the first, third, and fifth characters coming from $alpha and second, fourth, and sixth characters coming from $number.
You can use this function
<?php
public static function random_string($charsNo = 3, $NumbersNo = 3)
{
$character_set_array = array();
$character_set_array[] = array('count' => $charsNo, 'characters' => 'abcdefghijklmnopqrstuvwxyzasdsawwfdgrzvyuyiuhjhjoppoi');
$character_set_array[] = array('count' => $NumbersNo, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}
?>
What I need to add to this script to get 3 longest words from string?
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$max = $arr[0];
for ($i = 0; $i < count($arr); $i++) {
if (strlen($arr[$i]) > strlen($max)) {
$max = $arr[$i];
}
}
echo $max;
?>
Please help to modify the script. We have to not use the usort function.
The solution would be like this:
Use explode() to get the words of the string in an array
"Partially" sort the array elements in descending order of length
Use a simple for loop to print the longest three words from the array.
So your code should be like this:
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$count = count($arr);
for($i=0; $i < $count; $i++){
$max = $arr[$i];
$index = $i;
for($j = $i + 1; $j < $count; ++$j){
if(strlen($arr[$j]) > strlen($max)){
$max = $arr[$j];
$index = $j;
}
}
$tmp = $arr[$index];
$arr[$index] = $arr[$i];
$arr[$i] = $tmp;
if($i == 3) break;
}
// print the longest three words
for($i=0; $i < 3; $i++){
echo $arr[$i] . '<br />';
}
Alternative method: (Using predefined functions)
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr,function($a, $b){
return strlen($b)-strlen($a);
});
$longest_string_array = array_slice($arr, 0, 3);
// display $longest_string_array
var_dump($longest_string_array);
You need to create your own comparative function and pass it with array to usort php function.
Ex.:
<?php
function lengthBaseSort($first, $second) {
return strlen($first) > strlen($second) ? -1 : 1;
}
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr, 'lengthBaseSort');
var_dump(array_slice($arr, 0, 3));
It will output 3 longest words from your statement.
According to author changes:
If you have no ability to use usort for some reasons (may be for school more useful a recursive function) use following code:
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
function findLongest($inputArray) {
$currentIndex = 0;
$currentMax = $inputArray[$currentIndex];
foreach ($inputArray as $key => $value) {
if(strlen($value) > strlen($currentMax)){
$currentMax = $value;
$currentIndex = $key;
}
}
return [$currentIndex, $currentMax];
}
for($i = 0; $i < 3; $i++) {
$result = findLongest($arr);
unset($arr[$result[0]]);
var_dump($result[1]);
}
?>