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]);
}
?>
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";
}
?>
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);
This is my sample string (this one has five words; in practice, there may be more):
$str = "I want to filter it";
Output that I want:
$output[1] = array("I","want","to","filter","it");
$output[2] = array("I want","want to","to filter","filter it");
$output[3] = array("I want to","want to filter","to filter it");
$output[4] = array("I want to filter","want to filter it");
$output[5] = array("I want to filter it");
What I am trying:
$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output[$len][] = $text; // last element
$output[1] = $text_exp; // first element
This gives me the first and the last arrays. How can I get all the middle arrays?
more generic solution that works with any length word:
$output = array();
$terms = explode(' ',$str);
for ($i = 1; $i <= count($terms); $i++ )
{
$round_output = array();
for ($j = 0; $j <= count($terms) - $i; $j++)
{
$round_output[] = implode(" ", array_slice($terms, $j, $i));
}
$output[] = $round_output;
}
You can do that easily with regular expressions that give you the most flexibility. See below for the way that supports dynamic string length and multiple white characters between words and also does only one loop which should make it more efficient for long strings..
<?php
$str = "I want to filter it";
$count = count(preg_split("/\s+/", $str));
$results = [];
for($i = 1; $i <= $count; ++$i) {
$expr = '/(?=((^|\s+)(' . implode('\s+', array_fill(0, $i, '[^\s]+')) . ')($|\s+)))/';
preg_match_all($expr, $str, $matches);
$results[$i] = $matches[3];
}
print_r($results);
You can use a single for loop and if conditions to do
$str = "I want to filter it";
$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output1=$text_exp;
$output2=array();
$output3=array();
$output4=array();
$output5=array();
for($i=0;$i<count($text_exp);$i++)
{
if($i+1<count($text_exp) && $text_exp[$i+1]!='')
{
$output2[]=$text_exp[$i].' '.$text_exp[$i+1];
}
if($i+2<count($text_exp) && $text_exp[$i+2]!='')
{
$output3[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2];
}
if($i+3<count($text_exp) && $text_exp[$i+3]!='')
{
$output4[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2].' '.$text_exp[$i+3];
}
if($i+4<count($text_exp) && $text_exp[$i+4]!='')
{
$output5[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2].' '.$text_exp[$i+3].' '.$text_exp[$i+4];
}
}
I have an array something like that:
array('A','B','C','D','E');
and I want to make pairs of each value like that :
A, AB, ABC, ABCD, ABCDE
B, BC, BCD, BCDE
C, CD, CDE
D, DE
E
as an Array (ALL PAIRS SHOULD BE IN A SAME ARRAY).
And I have followed this Question:
How do I make pairs of array values?
But i'm not able to do that.
Please Help
For each of your inputs, loop between it and the end of the input array. For each result, add the range between the present and end inputs to your result.
$input = array('A', 'B', 'C', 'D', 'E');
$output = array();
for ($i = 0; $i < count($input); $i++) {
$row = array($input[$i]);
for ($j = $i + 1; $j < count($input); $j++) {
$row[] = implode('', range($input[$i], $input[$j]));
}
$output[] = $row;
}
$data = array('A','B','C','D','E');
$chars = count($data);
$combinations = array();
foreach ($data as $key => $startChar) {
$length = 0;
while ($length < $chars - $key) {
$combinations[] = implode(array_slice($data, $key, ++$length));
}
}
var_dump($combinations);
Looks like the format output:
$letters = array('A','B','C','D','E');
$result = array();
$x = 0;
while(count($letters) > 0) {
$l = array_shift($letters);
$result[$x][] = $l;
foreach($letters as $k => $letter){
$result[$x][] = $l . implode(array_slice($letters, 0, $k+1));
}
$result[$x] = implode(', ', $result[$x]);
$x++;
}
echo '<pre>';
print_r($result);