I want to create an array which has two columns. The output should contain only the existing letters in the word with their amounts.
The wanted output of the following code
a 3
s 2
p 1
What is wrong in the following PHP code?
<?php
$alpha = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','z','y');
$word = "saapas";
for ( $i = 0; $i < count($word); $i++ ) {
echo $word[$i] . "\n";
$table[$word[$i]][]++; // Problem here
}
// array_unique, array_combine and some method which can sort arrays by alphabets can be useful
PHP has extensive array functions that do much of the heavy lifting for this:
$keys = range('a', 'z');
$values = array_fill(0, 26, 0);
$freq = array_combine($keys, $values);
$word = "saapas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
$letter = strtolower($word[$i]);
if (array_key_exists($letter, $freq)) {
$freq[$letter]++;
}
}
print_r($freq);
Output:
Array
(
[a] => 3
[b] => 0
[c] => 0
[d] => 0
[e] => 0
[f] => 0
[g] => 0
[h] => 0
[i] => 0
[j] => 0
[k] => 0
[l] => 0
[m] => 0
[n] => 0
[o] => 0
[p] => 1
[q] => 0
[r] => 0
[s] => 2
[t] => 0
[u] => 0
[v] => 0
[w] => 0
[x] => 0
[y] => 0
[z] => 0
)
If you want to distinguish between uppercase and lowercase try:
$keys = array_merge(range('a', 'z'), range('A', 'Z'));
$values = array_fill(0, 52, 0);
$freq = array_combine($keys, $values);
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
$letter = $word[$i];
if (array_key_exists($letter, $freq)) {
$freq[$letter]++;
}
}
print_r($freq);
Or to count any characters:
$freq = array();
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
$letter = $word[$i];
if (array_key_exists($letter, $freq)) {
$freq[$letter]++;
} else {
$freq[$letter] = 1;
}
}
print_r($freq);
This works using your input characters array, but do you really want to build a static array for this task?
$table = array();
$count = strlen($word);
for ( $i = 0; $i < $count; $i++ ) {
$letter = $word[$i];
if ( !isset($table[$letter]) )
{
$table[$letter] = 0;
}
++$table[$letter];
}
Here's a method of doing the same thing, but utilizing PHP's native functions:
$ascii = count_chars($word, 1);
$keys = array_keys($ascii);
$chars = array_map('chr', $keys);
$charCount = array_values($ascii);
$table = array_combine($chars, $charCount);
Why complicate?
$string = 'the grey fox jumps over the lazy dog';
$words = explode(' ', $string);
foreach ($words as $key => $value)
{
$words[$key] = count_chars($value, 1);
}
echo '<pre>';
print_r($words);
echo '</pre>';
for ( $i = 0; $i < $alpha.length; $i++ ) {
$count = 0;
for($a = 0; $a < count($word); $a++)
{
if($word[$a] == $array[$i]
$count++;
}
if($count > 0)
echo $array[$i] . " " . $count . "\n";
}
So we use 2 for loops. A little inefficient that what your trying to do. One to check for each character of the alphabet. The second loop is to loop through the string and count the matches against the alphabet the first loop is on.
Edit:
Or you could add a zero to the line below and remove the echo from the loop. Which still requires another loop to display this table.
$table[$word[$i]][0]++;
try this out.it is a single iteration method and faster and simple!
<?php
$word = "saapas";
$result;
for ( $i = 0; $i < strlen($word); $i++ ) {
echo $word[$i] . "\n";
$result[$word[$i]]++; //make use of associative arrays to store the count for each alphabet.
}
foreach($result as $key => $value)//print each element inside the result array
{
print $key . " = " . $value . "<br />";
}
?>
count() doesn't quite work that way, you have to explicitly convert to an array if you want to use the count function. As for the $table array, you have an extra dimension (the []).
The following code should work (it is not optimal but should get you pointed in the right direction.)
$word = str_split("saapas");
for ( $i = 0; $i < count($word); $i++ ) {
$table[$word[$i]]++;
}
foreach ($table as $key => $value) {
print "$key $value\n";
}
Related
I have a task of sorting an array of numbers in both ascending and descending order. The challenge is, I can't use the built-in sort function, but loop through the array with for-loops instead.
I am a total newbie when it comes to PHP and this task straight off baffles me. Here is the code I'm supposed to work with:
<?php
$arr = $_GET['arr'];
$table = explode(',', $arr);
$count = count($table);
// What I tried to work with, didn't get to work:
for ($i = 0; $i < $count; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
if ($table[$i] > $table[$j]) {
$temp = $table[$i];
$table[$i] = $table[$j];
$table[$j] = $temp;
$asc = implode("," $temp);
}
}
}
echo "Ascending: $asc";
echo "Descending: $desc";
?>
Any clue why this doesn't run? At some point, I got the first (largest) number in the array with the echo, but don't really know what broke that either.
Move the line
$asc = implode(",", $table);
from its current location below the outer for loop and maybe add the line
$desc = implode(",", array_reverse($table));
to get the descending sort order.
Many ways to make it. One solution you will find in the code below. you will certainly notice that the sorting depends only on one operator. Therefore, you can build a function out of it by specifying the sorting as a parameter. function(array $array, string $sort) {}
DESC
$arr= array(112,21,130,140,2,42);
for($i=0; $i<count($arr)-1; $i++)
{
for($j=0; $j<count($arr)-1; $j++)
{
if($arr[$j] < $arr[$j+1]){
$temp= $arr[$j+1];
$arr[$j+1]= $arr[$j];
$arr[$j]= $temp;
}
}
}
print_r($arr);
Output:
Array
(
[0] => 140
[1] => 130
[2] => 112
[3] => 42
[4] => 21
[5] => 2
)
ASC
$arr= array(112,21,130,140,2,42);
for($i=0; $i<count($arr)-1; $i++)
{
for($j=0; $j<count($arr)-1; $j++)
{
if($arr[$j] > $arr[$j+1]){
$temp= $arr[$j+1];
$arr[$j+1]= $arr[$j];
$arr[$j]= $temp;
}
}
}
print_r($arr);
Output
Array
(
[0] => 2
[1] => 21
[2] => 42
[3] => 112
[4] => 130
[5] => 140
)
$tag=[25, 26];
$tagarray[]=[25,29,30,44,26];
I need a result of [29,30,44]. Here my main array is tagarray. and tested it with tag array. I need unmatched values from tagarray without any array function like array_diff().I want to compare both arrays and only provide the elements from tagarray which are not present in tag array.
$missings = [];
$matches = false;
for ( $i = 0; $i < count($tagarray); $i++ ) {
$matches = false;
for ($e = 0; $e < count($tag); $e++ ) {
if ( $tagarray[$i] == $tag[$e] ) $matches = true;
}
if(!$matches) array_push($missings,$tagarray[$i]);
}
dd($missings);
You need nested for loops to loop over each element of your array to filter, and for each of these elements, loop on the array containing the filters.
Since you do not want to use any of the array function, you need to use a boolean to check whether or not the index was to be filtered or not and make use of a 3rd array to store the filtered array.
Take a look:
$tag = [25, 26];
$tagarray = [25,29,30,44,26];
$filteredArray = [];
for($i = 0; $i < count($tagarray); ++$i){
$toRemove = false;
for($j = 0; $j < count($tag); ++$j){
if($tagarray[$i] == $tag[$j]){
$toRemove = true;
break;
}
}
if(!$toRemove){
$filteredArray[] = $tagarray[$i];
}
}
var_dump($filteredArray);
Output
array(3) {
[0]=>
int(29)
[1]=>
int(30)
[2]=>
int(44)
}
I would personally not choose this solution and go with Aksen's one, but since you do not want to use any array functions I assume that this is a school assignment and that you have no other choices ;)
If you don't want to use array_diff() then you can use in_array():
$res = [];
foreach($tagarray[0] as $val){
if (!in_array($val,$tag)) $res[] = $val;
}
print_r($res);
Output:
Array
(
[0] => 29
[1] => 30
[2] => 44
)
Demo
If $tagarray has more then 1 element:
$tag=[25, 26];
$tagarray[]=[25,29,30,44,26];
$tagarray[]=[25,22,11,44,26];
$res = [];
foreach($tagarray as $ind=>$tagar){
foreach($tagar as $val){
if (!in_array($val,$tag)) $res[$ind][] = $val;
}
}
Output:
Array
(
[0] => Array
(
[0] => 29
[1] => 30
[2] => 44
)
[1] => Array
(
[0] => 22
[1] => 11
[2] => 44
)
)
Demo
Third Without any inbuilt PHP array function:
$tagar_l = count($tagarray);
$tag_l = count($tag);
$tagar_0_l = count($tagarray[0]);
$res = [];
for($i = 0; $i<$tagar_l; $i++){
$res[] = $tagarray[$i];
for($j = 0; $j<$tagar_0_l; $j++){
for($k = 0; $k<$tag_l; $k++){
if ($tag[$k] === $tagarray[$i][$j]) unset($res[$i][$j]);
}
}
sort($res[$i]);
}
Demo
Via foreach loop:
$res = [];
foreach($tagarray as $ind=>$arr){
$res[] = $arr;
foreach($arr as $ind_a=>$val){
foreach($tag as $comp){
if ($comp === $val) unset($res[$ind][$ind_a]);
}
}
sort($res[$ind]);
}
Demo
I have several arrays.
example:
$a = Array(
[0] => #ID_1
[1] => #ID_2
[2] => #ID_3
)
$b = Array(
[0] => ABC
[1] => cde
[2] => fgh
)
$c = Array(
[0] => 000
[1] => 111
[2] => 222
)
How to concatenate these data fields using any foreach, for, while loop?
Expected result:
$result = '#ID_1 ABC 000';
I try something like this:
$result = '';
foreach($a as $aa) {
$result .= $aa ." ";
foreach ($b as $bb) {
$result .= $bb ." ";
foreach($c as $cc) {
$result .= $cc .'<br>';
}
}
}
but the result did not meet expectations.
Can anyone advise how to use foreach to chain these arrays together? Thank you. Thank you very much.
If you need foreach loop then use next code:
$res = [];
foreach($a as $ind=>$val){
$res[$ind] = $val." ".$b[$ind]." ".$c[$ind];
}
Demo
You can do something like this.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
$arrayLength = count($arr1);
$i = 0;
$result = [];
while ($i < $arrayLength)
{
$result[] = $arr1[$i]." ".$arr2[$i]." ".$arr3[$i];
$i++;
}
foreach($result as $item){
echo $item."<br/>";
}
According to what you're asking, you want to join elements with the key 0 from all arrays, then with the key 1 and so on, so instead of doing a foreach loop you could use a for loop using the key:
<?php
$a = Array(
0 => "#ID_1",
1 => "#ID_2",
2 => "#ID_3",
);
$b = Array(
0 => "ABC",
1 => "cde",
2 => "fgh"
);
$c = Array(
0 => 000,
1 => 111,
2 => 222
);
$length = sizeof($a);
$output = '';
for($i = 0; $i<$length; $i++) {
$output .= $a[$i] . ' / ' . $b[$i] . ' / ' . $c[$i] . '<br>';
}
echo $output;
?>
Outputs:
#ID_1 / ABC / 0
#ID_2 / cde / 111
#ID_3 / fgh / 222
Way to do this using foreach, if number of elements in each array is same.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
foreach($arr1 as $k => $item) {
echo "$item {$arr2[$k]} {$arr3[$k]}<br>";
}
using for loop this way would give you your expected result
<?php
$a = Array(
0 => '#ID_1',
1 => '#ID_2',
2 => '#ID_3'
);
$b = Array(
0 => 'ABC',
1 => 'cde',
2 => 'fgh'
);
$c = Array(
0 => '000',
1 => '111',
2 => '222'
);
$arrlengtha = count($a);
$arrla = $arrlengtha - 2;
$arrlengthb = count($b);
$arrlb = $arrlengthb - 2;
$arrlengthc = count($c);
$arrlc = $arrlengthc - 2;
for($x = 0; $x < $arrla; $x++) {
echo $a[$x]." ";
}
for($x = 0; $x < $arrlb; $x++) {
echo $b[$x]." ";
}
for($x = 0; $x < $arrlc; $x++) {
echo $c[$x]." ";
}
?>
I have one array like this :
$array='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}'
I want first split to two array like this :
$array[0]={b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1}
And
$array[1]={b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}
I change every array with this code
foreach ($b as $k => $m) {
if ($k % 2 == 0) {
$even[]= $m;
}
else {
$odd[] = $m;
}
}
$ff=array_combine($even,$odd);
I want output change like this
Array( Array[0] => ([b_price] => 9500 [b_discount] => 10 [mainPrice] => 95000 [total] => 95000 [title] =>obj1)
Array[1] => ([b_price] => 1500 [b_discount] => 15 [mainPrice] => 15000 [total] => 22500 [title] => obj2))
Two approaches:
-- using explode and array_map functions:
$str = '{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
$result = array_map(function($v){
$r = [];
$arr = explode(',', trim($v, '{}'));
foreach ($arr as $k => $v) {
if (!($k % 2)) $r[$v] = $arr[$k+1];
}
return $r;
}, explode('},{', $str));
print_r($result);
-- using additional preg_match_all and array_combine functions:
$str = '{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
$result = array_map(function($v){
preg_match_all('/([^,]+),([^,]+),?/', trim($v, '{}'), $m);
return array_combine($m[1], $m[2]);
}, explode('},{', $str));
print_r($result);
The output:
Array
(
[0] => Array
(
[b_price] => 9500
[b_discount] => 10
[mainPrice] => 95000
[total] => 95000
[title] => obj1
)
[1] => Array
(
[b_price] => 1500
[b_discount] => 15
[mainPrice] => 15000
[total] => 22500
[title] => obj2
)
)
you should change your needle, in your array string,
i have changed it with semicolon,
$arrayString='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1};{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
echo $arrayString;
echo "<pre>"; print_r (explode(";",$arrayString));
$b=explode(";",$arrayString);
foreach ($b as $k => $m) {
if ($k % 2 == 0) {
$even[]= $m;
}
else {
$odd[] = $m;
}
}
$ff=array_combine($even,$odd);
So, I write this decision. Maybe it can be more clear, but it works.
$array='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
/*Making array from string*/
$tmp_array = explode("},{", $array);
/*Removing { symbols*/
$tmp_array[0] = substr($tmp_array[0],1);
$tmp_array[1] = substr($tmp_array[1],0,-1);
/*Making arrays from string [0] and [1]*/
$tmp_array[0] = explode(',',$tmp_array[0]);
$tmp_array[1] = explode(',',$tmp_array[1]);
$new_array = [];
/*Creating associative arrays*/
for($a = 0; $a < count($tmp_array); $a++) {
$new_as_array = [];
for($i = 0; $i <= count($tmp_array[0]); $i+=2) {
if($i + 1 <= count($tmp_array[0])) {
$new_as_array[$tmp_array[$a][$i]] = $tmp_array[$a][$i + 1];
}
}
$new_array[] = $new_as_array;
}
print_r($new_array);
I need a PHP code to find longest contiguous sequence of characters in the string. So if b is coming together for maximum number of times your program should echo b and count
Example string:
aaabababbbbbaaaaabbbbbbbbaa
Output must be:
b 8
Using
- preg_match_all to get sequences of repeating characters,
- array_map along with strlen to get the string length of each sequence
- max to get the biggest value in the array.
Consider the following example:
$string = "aaabababbbbbaaaaabbbbbbbbaa";
preg_match_all('#(\w)\1+#',$string,$matches);
print_r($matches);
Will output
Array
(
[0] => Array
(
[0] => aaa
[1] => bbbbb
[2] => aaaaa
[3] => bbbbbbbb
[4] => aa
)
[1] => Array
(
[0] => a
[1] => b
[2] => a
[3] => b
[4] => a
)
)
Next we get the sizes for each string of repeating characters
$sizes = array_map('strlen', $matches[0]);
print_r($sizes);
Will output
Array
(
[0] => 3
[1] => 5
[2] => 5
[3] => 8
[4] => 2
)
Now let's get the biggest value of the $sizes array
print max($sizes);
Will give us
8
We need the key for the max value to pick up the letter
$maxKey = array_keys($sizes, max($sizes));
print $matches[1][$maxKey[0]];
Will output
b
Since you're looking for continuous sequences:
$string = 'aaabababbbbbaaaaabbbbbbbbaa';
$count = strlen($string);
if ($count > 0)
{
$mostFrequentChar = $curChar = $string[0];
$maxFreq = $curFreq = 1;
for ($i = 1; $i < $count; $i++)
{
if ($string[$i] == $curChar)
{
$curFreq++;
if ($curFreq > $maxFreq)
{
$mostFrequentChar = $curChar;
$maxFreq = $curFreq;
}
}
else
{
$curChar = $string[$i];
$curFreq = 1;
}
}
}
echo $mostFrequentChar . ' ' . $maxFreq;
$string = 'aaabababbbbbaaaaabbbbbbbbaa';
$occurrence = [];
$count = strlen($string);
for ($x = 0; $x < $count; $x++) {
if(isset($ocurrence[$string[$x]])) {
$ocurrence[$string[$x]]++;
} else {
$ocurrence[$string[$x]] = 0;
}
}
var_dump($occurrence);
This should do the trick.
<?php
$x = "aaaaaaabbbbbbbaaaacccccccaaaaaaaaaaaaaaaaabbbbbbaaaaadddddddddddddddddddddddddddddddddd";
$count = strlen($x);
$y =array();
$n =0;
$d =1;
$first = $x{1};
for($j = $d;$j < $count;$j++)
{
if($x{$j} == $first )
{
$y[$j] = $x{$j};
$first = $x{$j};
}
elseif($x{$j} != $first )
{
$y[$j] = ",".$x{$j};
$first = $x{$j};
}
}
$xy = implode("",$y);
$xy1 = explode(",",$xy);
$c_count = count($xy1);
$dg = 1;
for($g = 0;$g < $c_count;$g++)
{
$cnt = strlen($xy1[$g]);
$cntm = $xy1[$g];
$replace = $cntm{1};
if($cnt > $dg)
{
$ab = str_replace($cntm,$replace,$cntm);
$dg = $cnt.".".$ab ;
}
}
echo $dg;
?>