Auto switch between sentences - php

I would like my joomla site to automatically change which sentence it will echo to the user, so I wrote 3 different sentences:
$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";
I would like it to switch between the sentences, so I'm aware I can't just put $sentence1 in the echo but I don't know how to write it then. I have the echo line like this:
echo "Hey {user->name}." . "<br />" . $sentence1
By the way, the {user->name} is from Joomla's own "codes" so that worked fine :)

random greetings:
$sentence[1] = "Everything okay?";
$sentence[2] = "Have a good day";
$sentence[3] = "What are you doing today?";
echo "Hey {user->name}." . "<br />" . $sentence[rand(1,3)]

You could use a random function, such as mt_rand():
$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";
$nb = mt_rand(1, 3); // Gets a random number from 1 to 3
$sentence_shown = ${'sentence' . $nb}; // Equals $sentence1, $sentence2 or $sentence3
echo "Hey {user->name}." . "<br />" . $sentence_shown;
Or even better, put your three strings in an array :
$sentences = array();
$sentences[] = "Everything okay?";
$sentences[] = "Have a good day";
$sentences[] = "What are you doing today?";
$nb = mt_rand(0, 2); // Gets a random number from 0 to 2
$sentence_shown = $sentences[$nb];
echo "Hey {user->name}." . "<br />" . $sentence_shown;

In my opinion, you can put your 3 sentences or 3 strings in an array, and then you can print every sentence when you loop in it. Example:
$array = array(sentence1, sentence2, sentence3 , ... , sentence n);
for ($index = 0; $index < sizeof($array); $index++) {
echo 'This is sentence ' + index ':' + $array[index];
}

Related

splitting a large array() on a specific index

I have a form on my site for the users to post a results report into,
the report looks like this:
Nojoks's Tourney Bracket Tool Version 1.2.1.84
Tournament: 3/5 Backgammon 1:00pm
Date: 01/22/2017
Day: Sunday
Scheduled Start: 1.00pm PST
Actual Start: 20:00:30
Closed: 20:11:00
Host: Waiter ()
Number of Players: 15
1st place: poppop
1st place email: bobmitch1170#gmail.com
2nd place: Sarge
2nd place email: rgarvey5#hotmail.com
3rd place: Litigolfer
3rd place email: dostrow2008#gmail.com
3rd place: PhantomMask
3rd place email:
START POINTS
burnieboy 5
EU_BNL_Chris1 5
EU_IT_VIANG 5
GennaLee 5
happybear 5
MC_Vicky 5
merceaviles 5
MRC_cadet 5
poeticfool 5
UBG_Angel_D_8 5
UBG_sara1smoon 5
Litigolfer 60
PhantomMask 60
Sarge 90
poppop 120
STOP POINTS
this report is going to be identical everytime with some minor changes
I have already split this into an array with explode
$records = explode( PHP_EOL, $_POST['points'] );
$records = array_map('htmlspecialchars', $records );
$records = array_map ('trim', $records);
Then i have work on collecting the information from the top of the report like so:
// Get Date
$date = substr($records[2], 7, 10);
echo "<b>Tournament Date: </b>" . $date . "<br />";
// Get star time
$start_time = substr($records[4], 18, 7);
echo "<b>Tournament Start Time: </b>" . $start_time . "<br />";
now i need to work on everything from $records[20] down
what i need to do is simple enough i just do not know how to get to the correct part of my array first
I used to ask my users to post only the information from the START POINTS line down to STOP POINTS so to get my information out and split was simple i used:
foreach( $records as $record ) {
$lastSpace = strrpos( $record, ' ' );
$player = trim( substr( $record, 0, $lastSpace ) );
$points = trim( substr( $record, $lastSpace+1 ) );
this code will still work in this case if i can drop the index's 0 - 19 or just split the array into a new array $records1
P.S its this section in the report that is ever changing so to speak this report is from a online tournament hosting tool and each tournament has no set amount of players it can range from 8 upwards
I'm not sure I understand what you need. Perhaps something like this?
The idea is that you search for the indexes in the array which contain the start and end of the points and do a for loop to iterate only over those points.
$start = array_search("START POINTS", $records);
$end = array_search("END POINTS", $records);
$playerArray = [];
for ($i = $start+1;$i < $end;$i++) {
$parts = explode(" ",$records[$i]);
$player = $parts[0];
$points = $parts[1];
$playerArray = [ "player" => $player, "points" => $points ];
}
I managed to work this problem out for myself with thanks to #apokryfos your code still did not do quiet what i wanted so i used your codes and added them into what i have now,
Here is what i came up with:
// New try to split a full report in one go.
$points = $date = $day = $start_time = $host = $number_of_players = $fp_name = $fp_email = $sp_name = $sp_email = "";
// Explode the string at the end of each line,
// array map and remove any special chars then trim white space.
$records = explode( PHP_EOL, $_POST['points'] );
$records = array_map('htmlspecialchars', $records );
$records = array_map ('trim', $records);
// now each line of the NJ's report is in an array, call the array $records[index number]
// use substr( , , ) to find the needed part of the array indexs,
// I.E in the array $records on line 2 is the Date the actual needed information is the date dd/mm/yyyy,
// so we use $date = substr($records[2], 7, 10);
// from this string : Date: 01/18/2017 which is line 2 in records we get the 01/18/2017
// Get Date
$date = substr($records[2], 7, 10);
echo "<b>Tournament Date: </b>" . $date . "<br />";
// Get star time
$start_time = substr($records[4], 18, 7);
echo "<b>Tournament Start Time: </b>" . $start_time . "<br />";
// get Host name
$host = substr($records[7], 7);
echo "<b>Tournament Host: </b>" . $host . "<br />";
// get number of players
$number_of_players = substr($records[8], 20);
echo "<b> Number Of Players: </b>" . $number_of_players . "<br />";
echo "<br />";
// get the first place name and email address
$fplaceName = substr($records[10], 12);
echo "<b>1ST place: </b>" . $fplaceName . "<br />";
$fplaceEmail = substr($records[11], 18);
echo "<b>1ST place Email: </b>" . $fplaceEmail . "<br />";
// Get second place name and email
$splaceName = substr($records[12], 12);
echo "<b>2ND place Email: </b>" . $splaceName . "<br />";
$splaceEmail = substr($records[13], 18);
echo "<b>2ND place Email: </b>" . $splaceEmail . "<br />";
// get third place name and email
$tplaceName = substr($records[14], 12);
echo "<b>3RD place Email: </b>" . $tplaceName . "<br />";
$tplaceEmail = substr($records[15], 18);
$t1placeEmail = "fake#fake.com";
if($tplaceEmail == "") { // if third place email is empty add a generic fake email else continue as normal
$tplaceEmail = $t1placeEmail;
} ;
echo "<b>3RD place Email: </b>" . $tplaceEmail . "<br />";
echo "<hr /><br /><br />";
// Getting the players and points.
$parts1 = array_slice($records, 20, -1);
$end = array_pop($parts1);
$records = array_map('htmlspecialchars', $records );
$records = array_map ('trim', $records);
foreach( $parts1 as $record ) {
$lastSpace = strrpos( $record, ' ' );
$player = trim( substr( $record, 0, $lastSpace ) );
$points = trim( substr( $record, $lastSpace+1 ) );
echo $player . " " . " " . " " . $points . "<hr /><br />";
}
so what happens is, some user pastes the report as above in my original post,
and hits submit,
the form posts to my processing.php page,
I explode the whole post "string" into an array $records,
array_map the htmlspecialchars and trim the records,
then there is all the codes to extract the Date, time, host, number of players,
Then we get the 1st, 2nd, 3rd names and email address's,
then we get to sorting the playernames and points,
array_slice from the line after STOP POINTS index[20] also -1 for the STOP POINTS index,
pop the last line from the array "STOP POINTS" gone,
re do the array_map's on the new array,
run a foreach loop on the new array using a lastSpace strpos " " and the new array
then split player name from points....
if i run the finished code on the report given in my original post you get the following output:
Music Cafe Tournament Date: 01/22/2017 Tournament Start Time: 1.00pm
Tournament Host: Waiter () Number Of Players: 15
1ST place: poppop 1ST place Email: bobmitch1170#gmail.com 2ND place
Email: Sarge 2ND place Email: rgarvey5#hotmail.com 3RD place Email:
Litigolfer 3RD place Email: dostrow2008#gmail.com
burnieboy 5
EU_BNL_Chris1 5
EU_IT_VIANG 5
GennaLee 5
happybear 5
MC_Vicky 5
merceaviles 5
MRC_cadet 5
poeticfool 5
UBG_Angel_D_8 5
UBG_sara1smoon 5
Litigolfer 60
PhantomMask 60
Sarge 90
poppop 120
of course with the rule separating each name and points,
which is what i needed and now i can add all my sql statements and bingo.
please if anyone can see an easier or better way to achieve this goal i would love to see your edits and test them out

PHP: Extract word from string and get word count

I have tried for hours to figure this out, to no avail. I have searched and searched, with a lot of results saying to use an array. I can not use an array as this has not been covered in my class yet. Here is what I am to do:
I am to use a for loop to examine the characters using index variable.
When a blank character is found, this indicated the end of the word.
I then need to extract the word from the string and increment the word count, thus printing the word count and extracted word, continuing til the end of the sentence.
Then printing the total word count.
What I am stuck on is extracting the word. Here is what I have so far, which could very well be wrong but I am at my wits end here, so any little bit of push in the right direction would be great.
(Remember, I can not use arrays.)
$stringSentence = "The quick brown fox jumps over the lazy dog";
$wordcount = 1;
$blankCharacter = stripos($stringSentence, " ");
for ($i =0; $i<strlen($stringSentence);$i++)
{
$i. " ". $stringSentence{$i}."<br>";
}
if ($blankCharacter)
{
echo $wordcount++, " ";
echo substr($stringSentence,0,$blankCharacter);
}
Thanks for any help.
Have you considered just going through each individual letter to check for spaces and storing in a temporary buffer otherwise? One example:
$stringSentence = "The quick brown fox jumps over the lazy dog";
$buffer = '';
$count = 1;
$length = strlen($stringSentence);
for ($i = 0; $i < $length; $i++) {
if ($stringSentence{$i} !== ' ') {
$buffer .= $stringSentence{$i};
} else {
echo $count++ . ' ' . $buffer . ' ';
$buffer = '';
}
}
echo $count . ' ' . $buffer;
I'm not putting much explanation into my answer.. sort of a backwards approach of giving you the answer but it's up to you to understand how and why the above approach works.
Since this is home work I can't do it for you but you have an end bracket for one in the wrong place
Have a look at this sudo code and you should be in the right direction.
$blankCharacter = ' ';
for ($i =0; $i<strlen($stringSentence);$i++)
{
if (thisCharacter == $blankCharacter)
{
$wordcount++;
}
}
Arrays aren't that complicated! And a solution is very easy with it:
(Here I just explode() your string into an array. Then I simply loop through the array and print the output)
<?php
$stringSentence = "The quick brown fox jumps over the lazy dog";
$words = explode(" ", $stringSentence);
foreach($words as $k => $v)
echo "WordCount: " . ($k+1) . "| Word: $v<br>";
echo "Total WordCount: " . count($words);
?>
output:
WordCount: 1| Word: The
//...
WordCount: 9| Word: dog
Total WordCount: 9
If you want to read more about arrays see the manual: http://php.net/manual/en/language.types.array.php
EDIT:
If you can't use arrays, just use this:
Here I just loop through all characters of the sentence to check if it is either a space OR the end of the string. If the condition is true I print the word count + the substr from the last space until the current one. Then I also increment the word count with 1. At the end I simply print the total word count (note that I subtracted 1, because the last word will also add 1 to the count which is too much).
<?php
$stringSentence = "The quick brown fox jumps over the lazy dog";
$wordcount = 1;
$blankCharacter = 0;
for ($i = 0; $i < strlen($stringSentence); $i++) {
if($stringSentence[$i] == " " || $i+1 == strlen($stringSentence)) {
echo "WordCount: $wordcount | Word: " . substr($stringSentence, $blankCharacter, $i-$blankCharacter+1) . "<br>";
$blankCharacter = $i;
$wordcount++;
}
}
echo "Total WordCount: " . ($wordcount-1);
?>

Division with php

Im trying to get out an average value from a vote function.
<?php
$file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = str_split($textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum = $sum + intval($vote);
}
echo "Average: " . $sum;
?>
Simple by substitute (+) with a (/), and even tried a (%). But still getting error message.
Would appreciate alot if anyone could help me out and tell me what im doing wrong.
/thanks
Edit
Sidenote: Please read an explanation under "First answer given" further down below.
This version will take into account any blank lines in a file, if the content looks like:
1
2
3
// <- blank line
Sidenote: Please provide a sample of your text file. A comment has already been given to that effect.
PHP
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = array_filter(array_map("trim", file("textfile.txt")), "strlen");
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
First answer given
Using the following in a text file: (since no example of file content was given)
5
5
5
IMPORTANT NOTE: There should not be a carriage return after the last entry.
produced
Number of votes: 5
Average: 3
which is false, since there are 3 entries in the text file.
explode() should be used, and not str_split()
The following using the same text file produced:
Number of votes: 3
Average: 5
which is correct. In simple mathematics, averages are done by adding all numbers then dividing them by how many numbers there are.
In this case it's 3 numbers (all 5's) added equals 15, divided by 3 is 5.
Sidenote: The first line is not required $file = file("textfile2.txt");
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = explode("\n", $textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
Footnotes:
If the average comes out to 8.33333 and you would like it to be rounded off to 8, use:
echo "Average: " . floor($avg);
If the average comes out to 8.33333 and would like it to be as 9 you would use:
echo "Average: " . ceil($avg);
ceil() function
floor() function
You may be mixing in stuff that can't be divided, like text, etc. I don't know what your text file looks like. intval may be having a problem with arrays. You may try:
foreach ($textfill as $vote) {
if(is_int($vote) {
$sum += $vote;
}
}
echo "Average: " . $sum;
Lower school math says:
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
The average value is calculated by divide the sum with the number of votes. This line will print the average value:
echo "Average: " . $sum/count($textfill);

unexpected result in php output with larger strings

I am trying to create a binary/hexadecimal converter to convert a denary(base 10) number/value into binary and hexadecimal.
It works fine so far for binary until the input from the form is greater than 11 digits and over(string length), ruffly as it seems to variety. after 11 digits it starts adding " - " into the outcome. Im not sure were this is coming from as I don't have an " - " in the code.
I wasn't sure if this was something to do with large integers as I saw some other questions on that topic(not in php however it was java, so not sure if there is something simpler in php)
That said I was under the impression that form inputs were always strings.
To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric(). - from : http://www.php.net/manual/en/function.is-float.php
(haven't yet got to hexadecimal but needed to mention it as some of the following code contains parts for it.)
here is the php code (note: I do check user input just not added it yet)
$inpu = $_POST['number'];
$numinput = $_POST['number'];
if (is_numeric($numinput))
{
while ($numinput >= 1)
{
$binary .= $numinput % 2;
$numinput = $numinput / 2;
}
$mult = strlen($binary) % 4;
echo gettype($numinput) . "<br />";
echo gettype($binary) . "<br />";
echo gettype($mult) . "<br />";
echo $mult . "<br />";
while ($mult < 4)
{
$binary.= "0";
$mult++;
}
$revbinary = strrev($binary);
echo $inpu . " in binary = " . $revbinary ;
echo "<br /> <br />";
echo chunk_split($revbinary, 4);
echo "<br />" . gettype($revbinary) . "<br />";
echo gettype($inpu) . "<br />";
}
else
{
if (is_numeric($numinput))
{
echo "$numinput is over the max value of 255";
}
else
{
echo "your entry is not a vaild number <br />";
echo $numinput;
}
}
Im not looking for completed version of this code as you would ruin my fun, I am just wondering why there is a "-" being entered after 11 digits or so. It also did't add the symbol before I added :
$mult = strlen($binary) % 4;
echo $mult . "<br />";
while ($mult < 4)
{
$binary.= "0";
$mult++;
}
This was to split the binary into 4s ( 0011 1101 0010 0110 ).
Edit: wondered if this would be useful:
echo gettype($numinput); result double
echo gettype($binary); result string
echo gettype($mult); result integer
gettype($revbinary); result string
echo gettype($inpu); result string
still trying to work this out myself.
Any advice is much appreciated Thanks
I would suggest simply using decbin() and dechex(). Those are functions included in php, which do exactly what you're trying to accomplish.
You might want to check if it is a number first (like you are already doing).
Then cast it to an integer (through intval()) and then apply decbin() and dechex()
http://php.net/manual/de/function.decbin.php
http://www.php.net/manual/de/function.dechex.php
http://php.net/manual/de/function.intval.php

Bring last three words of a string to the beginning

I want to bring the last three words of a string to its beginning. For example, these two variables:
$vari1 = "It is a wonderful goodbye letter that ultimately had a happy ending.";
$vari2 = "The Science Museum in London is a free museum packed with interactive exhibits.";
Should become:
"A happy ending - It is a wonderful goodbye letter that ultimately had."
"With interactive exhibits - The Science Museum in London is a free museum packed."
Exploding, rearranging, and then imploding should work. See the example here
$array = explode(" ", substr($input_string,0,-1));
array_push($array, "-");
for($i=0;$i<4;$i++)
array_unshift($array, array_pop($array));
$output_string = ucfirst(implode(" ", $array)) . ".";
$split = explode(" ",$vari1);
$last = array_pop($split);
$last = preg_replace("/\W$/","",$last);
$sec = array_pop($split);
$first = array_pop($split);
$new = implode(" ",array(ucfirst($first),$sec,$last)) . " - " . implode(" ",$split) . ".";
Or similar should do the trick.
Make sure to love me tender. <3
function switcheroo($sentence) {
$words = explode(" ",$sentence);
$new_start = "";
for ($i = 0; $i < 3; $i++) {
$new_start = array_pop($words)." ".$new_start;
}
return ucfirst(str_replace(".","",$new_start))." - ".implode(" ",$words).".";
}
This will get you the exact same output that you want in only 2 lines of code
$array = explode(' ', $vari1);
echo ucfirst(str_replace('.', ' - ', join(' ', array_merge(array_reverse(array(array_pop($array), array_pop($array), array_pop($array))), $array)))) . '.';

Categories