loop in php function foreach - php

I try to get the result
danny love to eat orange and banana and grapes
Is it possible to get it through the function foreach
my Sample Code
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ';
//NOT THIS METHOD
// echo $var [0];
// echo ("and");
// echo $var [1];
// echo ("and");
// echo $var [2];
//Through this method
foreach ($var as $fruit) {
echo $fruit ;
echo ("and");
}
The result I get if i use foreach
danny love to eat orange and banana and grapes and
What's wrong ? :(

You're echoing 'and' one too many times. You don't want to echo 'and' if you're on the last element.
Try this instead.
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ' .implode('and',$var);

#bassxzero's answer is a great (In fact, I would recommend doing it that way over this way), but I wanted to show another way you could do this if you wanted to use a foreach loop still if you wanted to.
$var = array ("orange","banana","grapes");
$string = 'danny love to eat ';
//Through this method
foreach ($var as $fruit) {
$string .= $fruit. " and ";
}
$string = substr($string, 0, -5);
echo $string;
In my code, we are building a string that contains all the words that you want seperated by " and ". Then as soon as the loop is done, we use substr() to remove the very last " and " so that $string equals the string you were expecting.

Another solution could be
$var = array (" orange "," banana "," grapes ");
$str = 'danny love to eat ';
$total = count($var); // counts your aray
foreach ($var as $fruit) {
$total--; // decrements $total value
$str .= $total < 1 ? $fruit : $fruit.' and '; //if $total is reduced to 0 your loop is on the last repeat, so dont print 'and' anymore
}
echo $str;
Anyway implode way is the most elegant here.

Related

How to output repeat strings with looping and explode method only

e.g. "I think I got a long way to go to market."
In this case, I want to output
I 2
think 1
got 1
a 1
long 1
way 1
to 2
go 1
market 1
Code:
<?php
$tmp = explode (" ", $text);
echo "
My Words
Repetition
";
foreach ($tmp as $a)
{
echo "" $a."" ;
echo "" ;
}
echo ""
?>
You can try with
$text = "I think I got a long way to go to market.";
$tmp = explode (" ", $text);
foreach($tmp as $a){
$result[$a] += 1;
}
foreach($result as $value => $occurrences){
echo "$value $occurrences\n";
}

How to search for 2 or more matches in a single string?

I want to search for two or more words, but not able to match the exact word.
If I use some other function like stripos() I don't get the required output.
$string = "abc india ltd";
$Arr = array('xyz ab','abc india', 'pqr', 'yz lmn');
$Arr = implode('',$Arr);
if (preg_match_all("/$string/", $Arr)) {
echo '<b>'.'found'.'<font color="green">'.$string.'</font>'.'</b>';
}
or (Both Same, But want to avoid using inside a loop)
$string = "abc india ltd";
$Arr = array('xyz ab','abc india', 'pqr', 'yz lmn');
foreach ($Arr as $value) {
if (preg_match_all("/$string/", $value)) {
echo '<b>'.'found '.'<font color="green">'.$string.'</font>'.'</b>';
}
}
I think you want like this:-
<?php
$string = "abc india";
$Arr = array('xyz india','abc india', 'pqr', 'yz lmn',"xyz abc india");
foreach($Arr as $val){
$explode_string = explode(" ",$string);
$counter =0;
foreach($explode_string as $explode_str){
if(strpos($val,$explode_str) !== FALSE){
$counter +=1;
}
}
if($counter>=2){
echo $val. " have exact ".$counter. " word matches";
echo PHP_EOL;
}
}
Output:-https://eval.in/831808
Note:- check it with all possible test-cases and let us know, worked or not?
This leverages some smart array functions to keep the code block concise and avoid manually incrementing a counter:
Code: (Demo)
$input_string="abc india ltd";
$input_array=explode(' ',$input_string);
$search_array=array('xyz ab','abc india','ltd abc','yz lmn');
foreach($search_array as $search_string){
if(sizeof(array_intersect($input_array,explode(' ',$search_string)))>1){
echo "More than one word in $search_string was found in $input_string\n";
}
}
Output:
More than one word in abc india was found in abc india ltd
More than one word in ltd abc was found in abc india ltd
*note, array_intersect() generates a new array that only contains elements that exist in both provided arrays. sizeof() is an alias of count().

find position and frequency of words in sentences

I wanna find position and frequency of words in sentences.
for example :
You should eat two bananas before lunch and eat two before your dinner and then consume one banana.
so I will get the result :
You -> 1 -> position : 1
Should -> 1 -> position : 2
eat -> 2 -> position : 3, 9
etc.
For get the frequency I can use
array_count_values(str_word_count($str, 1))
but how to index to get the location?
thank you :)
Well, using your current function, you could just use a foreach loop, then gather them. Use explode and use their indices + 1. Example:
$str = 'You should eat two bananas before lunch and eat two before your dinner and then consume one banana.';
$count = array_count_values(str_word_count($str, 1));
$data = array();
// gather them first
foreach(explode(' ', $str) as $key => $value) {
$value = str_replace('.', '', $value);
$key = $key + 1;
$data[$value]['positions'][] = $key;
$data[$value]['count'] = $count[$value];
}
?>
<?php foreach($data as $word => $info): ?>
<p><?php echo "$word -> $info[count] -> Position: " . implode(', ', $info['positions']); ?></p>
<?php endforeach; ?>
$string = 'You should eat two bananas before lunch and eat two before your dinner and then consume one banana';
$array = explode ( ' ' , $string ) ;
$frequency = array_count_values ($array);
foreach ($frequency as $key => $value)
{
echo $key.' -> '.$value.' -> position : '.(array_search($key ,$array)+1).'</br>';
}

Search for string with the most number of occurrence [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
Is there any PHP function that will return which string (banana, apple, grapes) has the most number of occurrence within a given string? In this example it should return apple though orange has the one with the most number.
See code + explanation.
<?php
$interesting = array('banana', 'apple', 'grapes');
$string = "apple grapes apple banana otherwords more words apple grapes apple orange";
// Explode into array
$array = explode(" ", $string);
// Group the values
$count = array_count_values($array);
// Sort the grouping by highest occurence to lowest
arsort($count);
// Get the keys of the most occurring
$keys = array_keys($count);
// compare key against the $interesting array for what you're interested in
$most_occurring = '';
foreach ($keys as $i) {
if (in_array($i, $interesting, true)) {
$most_occurring = $i;
break;
}
}
// Print output
echo "Most occurring $most_occurring, $count[$most_occurring] occurences.";
?>
Although the answer by rurouni88 is very nice but it no longer caters for the added requirement, which is that not all words are important and you are specifying which words to look for. You can do
<?php
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
$words=array("banana", "apple", "grapes");
foreach($words as $word)
{
$counts[$word]=substr_count($string,$word);
}
arsort($counts);
reset($counts);
if($counts[0]>0)
echo key($counts); // apple
else
echo "Your words are not present";
?>
Fiddle
You can try this:
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
$array = explode(" ", $string);
$words = array_unique($array);
$counter = 0;
$returnWord = null;
foreach($words as $word){
$currentWordCount = substr_count($string, $word);
if($currentWordCount > $counter){
$counter = $currentWordCount;
$returnWord = $word;
}
}
echo "Most occurrences: ".$returnWord ." : ".$counter;
Most occurrences: orange : 7
EDIT:
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
$words = array("banana", "apple", "grapes");
$counter = 0;
$returnWord = null;
foreach($words as $word){
$currentWordCount = substr_count($string, $word);
if($currentWordCount > $counter){
$counter = $currentWordCount;
$returnWord = $word;
}
}
echo "Most occurrences: ".$returnWord ." : ".$counter;
Most occurrences: apple : 4
yes, it's called substr_count!
it accepts the string, the name of the occurrence and the substring to analyze.
for example, if you want to check the max number of occurrences in that string, you could build an array with all the names you want to check and then for every value call this function.
example source code:
// initialize your string
$string = "apple grapes apple banana otherwords more words apple grapes apple orange";
// make an array with all the string names
$occurrences = explode(" ", $string);
// remove duplicate entries from the array
$occurrences = array_unique($occurrences);
// for every name, in an associative position, count the number of that occurrence in our string
foreach ($occurrences as $occurrence) {
$count[$occurrence] = substr_count($string, $occurrence);
}
// let see what it contains
var_dump($count);
// print out where it finds the max number of occorrences
echo "max occurrence found here: " . array_search(max($count), $count);
The rurouni88's solution is good and elegant, but it has a little overhead due to sorting. For large data probably the best way is to write ad-hoc function in O(nm):
function max_occurrences($array, $valid) {
$count = array();
$maxValue = 0;
$maxEl = "";
foreach( $array as $v ){
if ( ! in_array($v, $valid, true) )
continue;
isset ( $count[$v] ) ? $count[$v]++ : $count[$v]=1 ;
if ( $count[$v] > $maxValue ) {
$maxValue = $count[$v];
$maxEl = $v;
}
}
return $maxEl;
}
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
echo max_occurrences(explode(" ",$string), array("apple","grapes", "banana"));

Sorting data in an array

I got an array which has 7 types of fruit:
$fruits = array(
"lemon",
"orange",
"banana",
"apple",
"cherry",
"apricot",
"Blueberry"
);
I don't know how to print out the data in a way that the outcome will like this:
<A>
Apple, Apricot <!--(Note that Apricot is followed by Apple in alphabetic order)-->
<B>
Banana
<C>
Cherry
<L>
Lemon
<O>
Orange
I am sorry that the question may be a bit difficult.
But please kindly help if you could.
I'd first use an array sorting function like sort(), and then create a loop that goes through the array and keeps track of what the first letter of the last word it output is - each time the first letter changes, output a new heading first.
Try this:
sort($fruit);
$lastLetter = null;
foreach ($fruit as $f) {
$firstLetter = substr($f, 0, 1);
if ($firstLetter != $lastLetter) {
echo "\n" . $firstLetter . "\n";
$lastLetter = $firstLetter;
}
echo $f . ", ";
}
There's some tidying up needed from that snippet, but you get the idea.
You can do this:
// make the first char of each fruit uppercase.
for($i=0;$i<count($fruits);$i++) {
$fruits[$i] = ucfirst($fruits[$i]);
}
// sort alphabetically.
sort($fruits);
// now create a hash with first letter as key and full name as value.
foreach($fruits as $fruit) {
$temp[$fruit[0]][] = $fruit;
}
// print each element in the hash.
foreach($temp as $k=>$v) {
print "<$k>\n". implode(',',$v)."\n";
}
Working example
This should do what you are looking for:
$fruits = array("lemon","orange","banana","apple","cherry","apricot","Blueberry");
//place each fruit in a new array based on its first character (UPPERCASE)
$alphaFruits = array();
foreach($fruits as $fruit) {
$firstChar = ucwords(substr($fruit,0,1));
$alphaFruits[$firstChar][] = ucwords($fruit);
}
//sort by key
ksort($alphaFruits);
//output each key followed by the fruits beginning with that letter in a order
foreach($alphaFruits as $key=>$fruits) {
sort($fruits);
echo "<{$key}>\n";
echo implode(", ", $fruits)."\n";
}

Categories