input name: DEVO AVIDIANTO PRATAMA
output: DAP
if the input three word , appears DAP
input name: AULIA ABRAR
output: AAB
if the input two words, appears AAB
input name: AULIA
output: AUL
if the input one word, appears AUL
<?php
$nama = $_POST['nama'];
$arr = explode(" ", $nama);
//var_dump($arr);die;
$jum_kata = count($arr);
//echo $jum_kata;die;
$singkatan = "";
if($jum_kata == 1){
//print_r($arr);
foreach($arr as $kata)
{
echo substr($kata, 0,3);
}
}else if($jum_kata == 2) {
foreach ($arr as $kata) {
echo substr($kata,0,2);
}
}else {
foreach ($arr as $kata) {
echo substr($kata,0,1);
}
}
?>
how to correct this code :
else if($jum_kata == 2) {
foreach ($arr as $kata) {
echo substr($kata,0,2);
}
to print AAB?
As a variant of another approach. Put each next string over the previous with one step shift. And then slice the start of a resulting string
function initials($str, $length=3) {
$string = '';
foreach(explode(' ', $str) as $k=>$v) {
$string = substr($string, 0, $k) . $v;
}
return substr($string, 0, $length);
}
echo initials('DEVO AVIDIANTO PRATAMA'). "\n"; // DAP
echo initials('AULIA ABRAR'). "\n"; // AAB
echo initials('AULIA'). "\n"; // AUL
demo
You could do:
elseif ($jum_kata == 2) {
echo substr($kata[0],0,1);
echo substr($kata[1],0,2);
}
This will just get the first character of the first word, and then two characters from the next word.
You are returning two characters from each word which is why you get AUAB.
Related
I want to count the number of occurrences of each character in a string and print the ones that occur at least Y times.
Example :
Examples func(X: string, Y: int):
func("UserGems",2) => ["s" => 2, "e" => 2]
func("UserGems",3) => []
This what I could achieve so far:
$str = "PHP is pretty fun!!";
$strArray = count_chars($str, 1);
$num = 1;
foreach ($strArray as $key => $value) {
if ($value = $num) {
echo "The character <b>'".chr($key)."'</b> was found $value time(s)
<br>";
}
}
Firstly, you need to list all letters count with separately and to calculate it. Also, you need to calculate elements equal to count which is your find. I wrote 3 types it for your:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
So, it is very short version
function check($string,$count = 1) {
$achives = [];
$strArray = count_chars($string, 1);
array_walk($strArray,function($cnt,$letter) use (&$achives,$count){
$cnt!==$count?:$achives[chr($letter)] = $cnt;
});
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",3));
But it is exactly answer for your question:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = str_split($string, 1);
foreach($strArray as $index => $char ){
$strings[$char] = isset($strings[$char])?++$strings[$char]:1;
}
if($count) {
foreach($strings as $char => $cnt) {
if($cnt==$count) {
$achives[$char] = $cnt;
}
}
}
return $achives;
}
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
You can simply do this with php str_split() and array_count_values() built in functions. i.e.
$chars = str_split("Hello, World!");
$letterCountArray = array_count_values($chars);
foreach ($letterCountArray as $key => $value) {
echo "The character <b>'".$key."'</b> was found $value time(s)\n";
}
Output
Im creating a function to check whether a string contains a specific character prefixed,I need to validate the text based on two conditions.
1.if the string contains character + prefixed ,i have to show the text in output without prefix +.
eg:
"we have dinner +today"
output:
"we have dinner today"
2.if the string contains character - prefixed ,i have to show the text in output removing the whole text prefixed with -.
eg:
"we have dinner -today"
output:
"we have dinner".
I will pass an extra parameter called length in this function ,If the string length is less than the given length then the string will be removed.
eg:
length=4;
eg:
"we have dinner -today"
output:
"have dinner".
eg:
"we have dinner +today"
output:
"have dinner today".
The function i have created so far is
$fulltext="-through the +use of the +tab +key";
$length=4;
function checkstring($fulltext,$length)
{
$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value)
{
if(strlen($value) < $length)
$fulltext= str_replace(" ".$value." " ," ",$fulltext);
}
return $fulltext;
}
print_r(checkstring($fulltext,$length));
The output should be "use tab key"
You can iterate over the words and check if the conditions are checked to keep in the sentence.
$fulltext = "-through the +use of the +tab +key";
$length = 4;
function checkstring($fulltext, $length)
{
$words = preg_split('~\s~',$fulltext);
$remains = [];
foreach ($words as $word)
{
if (strpos($word, '-') === 0) {
continue;
}
if (strpos($word, '+') === 0) {
$word = substr($word, 1);
}
elseif (strlen($word) <= $length) {
continue;
}
$remains[] = $word;
}
return trim(implode(' ', $remains));
}
echo checkstring($fulltext, $length);
Output :
use tab key
View the online demo.
You can use this
if(ctype_alnum($fulltext)) {
echo 'Does not contain symbols';
} else {
echo 'Contains symbols';
}
One way is to use regular expressions to find matching string with correct length and prefixed symbol. If the prefix equals '+' you can then replace the match with string without prefix.
Take a look at preg_replace_callback() and example below.
/* a unix-style command line filter to convert uppercase
* letters at the beginning of paragraphs to lowercase */
<?php
$line = "<p>Start of the paragraph</p>";
$line = preg_replace_callback(
'|<p>\s*\w|',
function ($matches) {
return strtolower($matches[0]);
},
$line
);
echo $line;
?>
function checkstring($fulltext, $length)
{
$stringArray = explode(" ", $fulltext);
foreach ($stringArray as $value) {
if ($value[0] == "-") {
$fulltext = str_replace($value, " ", $fulltext);
} else if ($value[0] == "+") {
$fulltext = str_replace($value, substr($value, 1), $fulltext);
}
if (strlen($value) < $length)
$fulltext = str_replace(" " . $value . " ", " ", $fulltext);
}
return $fulltext;
}
Here is the complete function
Using regex
function checkstring(string $fulltext,int $length){
$matches = []; preg_match_all('/[+|-](.[\w]+)/',$fulltext,$matches);
$text = "";
if(isset($matches[1]) && count($matches[1]) > 0)
for($i=0;$i<count($matches[1]);$i++)
if($matches[0][$i][0] == "+" && ($matches[0][$i][0] == "+" && strlen($matches[1][$i]) < $length))
$text .= $matches[1][$i] . " ";
return trim($text);
}
$fulltext="-through the +use of the +tab +key";
$length = 4;
echo checkstring($fulltext,$length);
Output
use tab key
I'm sorry for the uncreative title.
I'm trying to group my array alphabetically. The accepted answer in this question (by Hugo Delsing) helped greatly to my task, but I still want to take things a bit further...
here's my current code:
$records = ['7th Trick', 'Jukebox', 'Dynamyte', '3rd Planet'];
$lastChar = '';
sort($records, SORT_STRING | SORT_FLAG_CASE);
foreach($records as $val) {
$char = strtolower($val[0]);
if ($char !== $lastChar) {
if ($lastChar !== '') echo "</ul>";
echo "<h2>".strtoupper($char)."</h2><ul>";
$lastChar = $char;
}
echo '<li>'.$val.'</li>';
}
echo "</ul>";
I want to make things so that non-alphabetic items would get grouped together instead of separated individually.
example:
"7th Trick" and "3rd Planet" get grouped together as non-alphabetic instead of displayed separately under "7" and "3" category respectively.
any idea how to do it?
You can just add one line to your existing code to accomplish this.
$char = strtolower($val[0]);
// Convert $char to one value if it isn't a letter
if (!ctype_alpha($char)) $char = 'Non-alphabetic';
if ($char !== $lastChar) {
The rest of it should work the same.
Remove the alphas from the array and show them after printing the alphas.
<?php
$records = ['7th Trick', 'Jukebox', 'Dynamyte', '3rd Planet'];
$lastChar = '';
sort($records, SORT_STRING | SORT_FLAG_CASE);
$alpha = array();
$non_alpha = array();
foreach($records as $val) {
if (ctype_alpha($val[0])) {
$alpha[] = $val;
} else {
$non_alpha[] = $val;
}
}
foreach($alpha as $val) {
$char = strtolower($val[0]);
if ($char !== $lastChar) {
if ($lastChar !== '') echo "</ul>";
echo "<h2>".strtoupper($char)."</h2><ul>";
$lastChar = $char;
}
echo '<li>'.$val.'</li>';
}
echo "</ul>";
if (sizeof($non_alpha) > 0) {
echo "<h2>Digits</h2><ul>";
foreach ($non_alpha as $val) {
echo '<li>'.$val.'</li>';
}
echo "</ul>";
}
function PigLatin($sentence)
{
$vowelSufix = "way";
$consonantSufix = "ay";
$vowelArray = array('a','e','o','u','i');
$finalword;
$wordArray = explode(' ', $sentence);
foreach ($wordArray as $value)
{
$word = $value;
$consonant = $word[0];
if (in_array($word[0], $vowelArray))
{
$finalword = substr($word, 1). $word[0]. $vowelSufix. "<br />";
}
else
{
for ($i=1; $i <strlen($word) ; $i++)
{
if (in_array($word[$i], $vowelArray))
{
$finalword = substr($word, $i). $consonant. $consonantSufix . "<br />";
}
else
{
$consonant .= $word[$i];
}
}
}
if ($finalword[0] == $finalword[1])
{
return substr($finalword, 1);
}
$finalword .= $finalword;
}
var_dump($wordArray);
}
So basicly it is giveing me the follow errors "Uninitialized string offset".I know this error comes because i am useing the arrays not proberly but i am stuck, Can someone please help me?
Your script doesn't handle the case where $word is empty, which will happen if you have two spaces in a row in the sentence. If $word is an empty string, $word[0] will get the error you reported, because there is no such character in the string.
Change the loop to:
foreach ($wordArray as $word)
{
if ($word === '') {
continue;
}
This will skip empty words. Note also that you don't need separate variables $value and $word.
I am looking to echo comma separated elements of an array e.g:
Element1, Element2, Element3, Element4, Element5, Element6
However, for the purposes of keeping the echoed elements neat, I might need to go to a new line after the each second element of each line e.g
Element1, Element2,
Element3, Element4,
Element5, Element6
As is I am doing:
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
echo implode(' ,', $labels_array);
?>
And obviously getting:
Element1, Element2, Element3, Element4, Element5, Element6
How then do i do a newline after each second element of a line using implode() or otherwise?
<?php
$labels = array('Element1', 'Element2', 'Element3', 'Element4', 'Element5', 'Element6');
# Put them into pairs
$pairs_array = array_chunk($labels, 2);
# Use array_map with custom function
function joinTwoStrings($one_pair) {
return $one_pair[0] . ', ' . $one_pair[1];
}
$pairs_array = array_map('joinTwoStrings', $pairs_array);
echo implode(',' . PHP_EOL, $pairs_array);
You can use foreach to achive it, im pasting code for you which will give you your desired output
<?php
$labels = array("Element1", "Element2", "Element3", "Element4", "Element5","Element6");
$key = 1;
$lastkey = sizeof($labels);
foreach($labels as $value)
{
if($key%2)
{
if($key==$lastkey)
{
echo $value;
}
else
{
echo $value.",</br>";
}
}
else
{
if($key==$lastkey)
{
echo $value."</br>";
}
else
{
echo $value.",</br>";
}
}
$key++;
}
?>
untested, but something like this should work
$i = 1;
foreach($labels as $label) {
echo $label;
// add a comma if the label is not the last
if($i < count($labels)) {
echo ", ";
}
// $i%2 is 0 when $i is even
if($i%2==0) {
echo "<br>"; // or echo "\n";
}
$i++;
}
For the sake of fancy:
$labels_array=array("Element 1","Element 2","Element 3","Element 4","Element 5","Element 6");
echo implode(",\n",array_map(function($i){ // change to ",<br />" for HTML output
return implode(", ",$i);
},array_chunk($labels_array,2)));
Online demo
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
for($i=0;$i<count($labels_array);$i++)
{ echo($labels_array[$i]);
if($i % 2 != 0)
{
echo("\n");
}else{echo(",");}
}
?>
$i = 1;
$str = '';
foreach($labels AS $label)
{
$str += "$label, ";
if ($i % 2 == 0)
{
$str += "\n";
}
$i++;
}
//Remove last 2 chars
$str = substr($str,0,(strlen($str)-2));
Unless you need the array for something else, this just builds the string...
<?php
$labels = Requisitions::getLabelNames($id);
$s='';
$i=0;
$l=count($labels);
foreach($labels as $label){
$s.=$label['name'];
// Append delimeter. Makes sure every second, and the last one, will be a line break
$s.=((++$i%2)&&($l!=$i))?' ,':"\n";
}
echo $s;
?>
If you do need the array for something, create it first and modify above as needed.