How can I achieve this in php string to bbbvvvvzzxxc => 3v4v2z2xc - php

How can I achieve php char count with php :
input : bbbvvvvzzxxc
output : 3b4v2z2xc
I try this code :
$str = "aabbbccaaaac";
$arr1 = str_split($str);
$count=1;
foreach($arr1 as $key=>$char) {
if($key==0){
$pre=$char;
}
if($pre==$char){
$count++;
} else{
$count=1;
$pre=$char;
}
echo $pre.'---'.$char.'__';
if($pre != $char){
echo $char. $count ;
} else {
// echo $char;
}
}
but not working :
its simple to set count of character

$str = "aabbbccaaaac";
$arr1 = str_split($str);
$count=0;
$pre = '';
$result = ''; // our result string
foreach($arr1 as $char){
if($char == $pre){
$count++;
}else{
if($count > 0){ // To check whether it was the first iteration
$result .= $count.$pre;
}
$count = 1;
$pre = $char;
}
}
$result .= $count.$pre; // For last iteration
echo $result;

Related

PHP look-and-say sequence

I'm trying to code Conway look-and-say sequence in PHP.
Here is my code:
function look_and_say ($number) {
$arr = str_split($number . " ");
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
return $res;
}
As I run the function, look_and_say(9900) I am getting value I expected: 2920.
My question is for assigning $arr to be $arr = str_split($number) rather than $arr = str_split($number . " "), the result omits the very last element of the $arr and return 29.
Is it normal to add empty space at the end of the $arr foreach to examine the last element or is there any better way to practice this code - besides regex way.
There are 2 methods I was able to come up with.
1 is to add concatenate at the result after the loop too.
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
$res .= $count . $target;
return $res;
}
And the 2nd one is to add another if clause inside the loop and determine the last iteration:
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
$i=0;
$total = count($arr);
foreach($arr as $num){
if($i == ($total-1))
{
$count++;
$res .= $count . $target;
}
elseif($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
$i++;
}
return $res;
}
I want to suggest you other way using two nested while loops:
<?php
function lookAndSay($number) {
$digits = str_split($number);
$result = '';
$i = 0;
while ($i < count($digits)) {
$lastDigit = $digits[$i];
$count = 0;
while ($i < count($digits) && $lastDigit === $digits[$i]) {
$i++;
$count++;
}
$result .= $count . $lastDigit;
}
return $result;
}

PHP inside foreach issue

I have this foreach :
<?php foreach ($manufacturers as $key => $manufacturer) {
if($manufacturer->virtuemart_manufacturercategories_id == 1){
$lang = 'heb'; //Hebrew
} else {
$lang = 'eng'; //English
}
//add to letter list
$letter = mb_substr($manufacturer->mf_name, 0, 1, 'UTF-8');
${'html_letters_'.$lang}[] = $letter;
/*
echo '<pre>';
print_r($manufacturer);
echo '</pre>';*/
$link = JROUTE::_('index.php?option=com_virtuemart&view=category&virtuemart_manufacturer_id=' . $manufacturer->virtuemart_manufacturer_id);
${'html_manufacturers_'.$lang} .= '<div class="manufacturer" data-lang="'.$lang.'" data-letter="'.$letter.'"><a href="'.$link.'">';
?>
<?php
if ($manufacturer->images && ($show == 'image' or $show == 'all' )) {
${'html_manufacturers_'.$lang} .= $manufacturer->images[0]->displayMediaThumb('',false);
}
if ($show == 'text' or $show == 'all' ) {
${'html_manufacturers_'.$lang} .= '<div>'.$manufacturer->mf_name.'</div>';
}
${'html_manufacturers_'.$lang} .= '</a>
</div> <!-- /manufacturer -->';
if ($col == $manufacturers_per_row){
$col = 1;
} else {
$col++;
}
}
?>
How i check if i have more then 2 same letters and unset all others but keep one.
The output for letter is :
AABCHKIUKP
I want this will be :
ABCHKIUKP
How i do this ?
EDIT: I have updated all the foreach code. The issue is if i have more then same start letter in name EG:Aroma,Air the loop the take the first letter A and foreach him 2 times, i want to show only one if there even 10 same start letter in name .
Thanks.
When I understand you right ... just use an array
<?php
$letters = array();
foreach ($manufacturers as $key => $manufacturer) {
....
$letter = mb_substr($manufacturer->mf_name, 0, 1, 'UTF-8');
$letters[] = $letter;
}
$uni = array_unique($letters)
echo implode('',$uni);
$s = 'AABCHKIUKP';
$letters = $letters = preg_split('/(?<!^)(?!$)/u', $s); //utf8
$prev_letter = '';
$temp = '';
foreach($letters as $key => $letter) {
if (!($letter === $prev_letter)) {
$temp .= $letter;
}
$prev_letter = $letter;
}
echo $temp;
Result:
ABCHKIUKP
Info about breaking a utf8 string to an array you can find at comments here mb_split.
To strip ONLY same consecutive chars you can use this:
function stripConsecutiveChars( $string ) {
// creates an array with chars from the string
$charArray = str_split( $string );
// saves the last char thats on the new string
$lastChar = "";
// variable for the new string to return
$returnString = "";
foreach( $charArray as $char ) {
if( $char === $lastChar ) continue;
$lastChar = $char;// save current char
$returnString .= $char;// concat current char to new string
}
return $returnString;
}
$string = "AABCHKIUKP";
echo stripConsecutiveChars( $string );
In your example you could try this:
...
$letter = mb_substr( $manufacturer->mf_name, 0, 1, 'UTF-8' );
$lastLetter = end( ${'html_letters_' . $lang} );//point to last element in array
reset( ${'html_letters_' . $lang} );// reset the pointer
if( $letter === $lastLetter ) {
// i guess you just want to continue?
continue;
}
...
OUTPUT:
ABCHKIUKP

Comma separated string to parent child relationship array php

I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';

how can i use python's like "For loop" in php to reverse string?

Here is python code:
def is_palindrome(s):
return revers(s) == s
def revers(s):
ret = ''
for ch in s:
ret = ch + ret
return ret
print is_palindrome('RACECAR')
# that will print true
when i convert that function to php.
function is_palindrome($string){
if (strrev($string) == $string) return true;
return false;
}
$word = "RACECAR";
var_dump(is_palindrome($word));
// true
Both functions works fine but, how can i revers string with php in loop ??
$string = str_split(hello);
$output = '';
foreach($string as $c){
$output .= $c;
}
print $output;
// output
hello
//i did this,
that's work find but is there any way to do that in better way ?
$string = "hello";
$lent = strlen($string);
$ret = '';
for($i = $lent; ($i > 0) or ($i == 0); $i--)
{
$ret .= $string[$i];
#$lent = $lent - 1;
}
print $output;
//output
olleh
Replace
$output .= $c;
with
$output = $c . $output;
Can't be shorter I guess. With a loop :)
$word = "Hello";
$result = '';
foreach($word as $letter)
$result = $letter . $result;
echo $result;
I don't try that code, but I think that it should work:
$string = "hello";
$output = "";
$arr = array_reverse(str_split($string)); // Transform "" to [] and then reverse => ["o","l","l,"e","h"]
foreach($arr as $char) {
$output .= $char;
}
echo $output;
Another way:
$string = "hello";
$output = "";
for($i = strlen($string); $i >= 0; $i--) {
$output .= substr($string, $i, 1);
}
echo $output;
strrev() is a function that reverses a string in PHP.
http://php.net/manual/en/function.strrev.php
$s = "foobar";
echo strrev($s); //raboof
If you want to check if a word is a palindrome:
function is_palindrome($word){ return strrev($word) == $word }
$s = "RACECAR";
echo $s." is ".((is_palindrome($s))?"":"NOT ")."a palindrome";

php find number of occurances (number of times)

can someone help with this?
I need the following function to do this...
$x = 'AAAABAA';
$x2 = 'ABBBAA';
function foo($str){
//do something here....
return $str;
}
$x3 = foo($x); //output: A4B1A2
$x4 = foo($x2);//output: A1B3A2
substr_count is your friend
or rather this
function foo($str) {
$out = '';
preg_match_all('~(.)\1*~', $str, $m, PREG_SET_ORDER);
foreach($m as $p) $out .= $p[1] . strlen($p[0]);
return $out;
}
function foo($str) {
$s = str_split($str);
if (sizeof($s) > 0) {
$current = $s[0];
$output = $current;
$count = 0;
foreach ($s as $char) {
if ($char != $current ) {
$output .= $count;
$current = $char;
$output .= $current;
$count = 1;
}
else {
$count++;
}
}
$output .= $count;
return $output;
}
else
return "";
}

Categories