I have developed this small code to check if 2 text, one from a database and the other from an outside imput have common words.
The problem is that I get a message "Argument is not an array".
I cannot see where is the problem.
I also need to check if the 2 messages if should have the same words are in the same sequence.
Please help to understand where is the mistake.
Thanks
$checkMsg=strip_tags($_POST['checkMsg']); // message from input form
$message // message from database
$MsgWords = preg_split("/[\s,]+/", $checkMsg);
if(!empty($checkMsg)){
foreach ($MsgWords as $Neword)
{ $Neword = trim($Neword);
echo " $Neword";
}
$word = preg_split("/[\s,]+/", $message);
foreach ($word as $currentWord)
{
$currentWord = trim($currentWord);
echo " $currentWord";
}
$intersect=array_intersect( $Neword ,
$currentWord);
echo" Your common words are: $intersect";}else{echo "No common words";}
As others have said you're comparing the strings not the array. Your code should be something like this (you'll have to probably change this a little its just an example)
$checkMsg=strip_tags($_POST['checkMsg']); // message from input form
$message // message from database
$MsgWords = preg_split("/[\s,]+/", $checkMsg);
if(!empty($checkMsg)){
$intersect=array_intersect($message,$MsgWords);
if (count($intersect)>1) {
//only show output if there are matches
echo "Words in common are:<br />";
foreach ($intersect as $Neword) {
$Neword = trim($Neword);
echo $Neword."<br />";
}
} else {
echo "There are no words in common";
}
}
Okay, so firstly you're looping through the two arrays and changing the value, but the way you have it, you are just changing a temp copy of the value, not the value in the array. To do that, you need to use the & sign in the foreach() to tell it to use a reference variable in the loop, like this:
foreach ($MsgWords as &$Neword) { //added the & sign here.
$Neword = trim($Neword);
}
Do the same thing to the other foreach() loop too.
Secondly, your array_intersect() call is looking at the single strings, not at the whole arrays. You need it to look at the arrays:
//your incorrect version:
$intersect=array_intersect( $Neword, $currentWord);
//corrected version, using your variable names.
$intersect=array_intersect( $MsgWords, $word);
That should solve your problems.
[EDIT]
Also, note the array_intersect() outputs an array (ie the array of the intersection between the two input arrays). You can't use echo() to print an array directly. If you try, it will just show the word 'Array'. You need to convert it into a string first:
//your incorrect code.
echo "Your common words are: $intersect";
//corrected code:
echo "Your common words are: ".implode(',',$intersect);
I would also note that your coding style is very messy and hard to read. I strongly recommend trying to tidy it up; follow some kind of indentation and variable naming rules. Otherwise it will be very hard to maintain.
Related
I am having input as Word "CODE"
and I want to get output as "CCOCODCODE"
Please help me with the logic to print this output.
Thanks.
It's rather simple. Looking at your pattern, you need to concatenate all possible prefixes of CODE one after the other. So, maintain a result variable and keep concatenating substrings with 0 as the start point and end point being each index in the string.
<?php
$str = 'CODE';
$result = '';
for($i=0;$i<strlen($str);++$i){
$result .= substr($str,0,$i+1);
}
echo $result;
Try to avoid loops whenever you can.
Short and simple does the trick :-)
<?PHP
$Text = 'CODE';
echo implode(array_map(function($Position) use ($Text) { return substr($Text,0,$Position+1); },array_keys(str_split($Text))));
I have one variable that comes from a database.
I then want to check whether that value is the same of one of the values in an array.
If the variable matches one of the array values, then I want to print nothing, and if the variable does not match one of the array values, then I want to print something.
This is the code I have been trying without luck, I know that contains is not valid code, but that is the bit I cannot find any info for:
<?php
$site = getStuff();
$codes = array('value2', 'value4');
if ($codes contains $site)
{
echo "";
}
else
{
echo "something";
?>
So if the database would return value1 for $site, then the code should print "something" because value1 is not in the array.
The function you are looking for is in_array.
if(in_array($site, array('value2', 'value4')))
if(!in_array($site,$codes)) {
echo "something";
}
To provide another use way to do what the other answers suggest you can use a ternary if
echo in_array($site, $codes)?"":"something";
How do I join a dynamic var to an existing var?
For example:
My code:
<?
// Gets value from url. In this example c is 1.
$c = $_GET[c];
// Multiple static questions will be pulled from a list.
// I use two as an example below.
$Q1 = "Is this question one?";
$Q2 = "so this must be question two then?"
echo "$c: ";
echo "Q$c"; // returns "Q1" but not the string above.
echo '$Q.$c"; // returns the val 1
?>
How do I join the two together and get it to return the appropriate string?
Instead of dynamic variable names, use an array that holds multiple values.
$num = $_GET['c'];
$questions = array(
"Is this question one?",
"so this must be question two then?"
);
echo "$num: ";
echo "Q$num";
echo $questions[$num];
There are many, many reasons to prefer arrays to "variable variables". One is that it's a cinch to loop over all the items in an array:
foreach ($questions as $num => $question) {
echo "Q$num: $question\n";
}
Another is that you can calculate the size of an array.
echo "There are " . count($questions) . " total questions.";
Another is that you can easily modify them. There are lots and lots and lots of ways to manipulate arrays which you could never do with a crude tool like variable variables.
// Add a new question to the array.
$questions[] = 'Question 3: Who are you?!';
// Remove duplicate questions.
$questions = array_unique($questions);
It looks like what you're really looking for is an array:
$questions = array("Question 0", "Question 1", "Question 2");
$q = 1;
echo $questions[$q]; //"Question 1"
Otherwise, you're going to have to use some var-var nasty hackiness (don't do this):
echo ${'Q' . $c};
Also, $_GET[c] should be $_GET['c'] unless c is actually a constant (and I hope it's not since c would be a terrible name for a constant). And you should use isset rather than assuming that the c key exists in $_GET
Full example:
$questions = array("Question 0", "Question 1", "Question 2");
$c = (isset($_GET['c'])) ? (int) $_GET['c'] : null;
if (isset($questions[$c])) {
echo "The question is: " . $questions[$c];
} else {
echo "The question was not found";
}
You should probably also be aware of the draw backs of short open tags. If ever a server has them disabled, all of your PHP code is going to break. Typing 3 extra characters doesn't seem worth that risk. (Though it is of course really easy to just mass find/replace <? -> <?php.)
I'm not sure I get what you meant but I think this is the anwer:
<?php
$var = "Q".$_GET['c'];
echo $$var; // take care of the double dollar sign
?>
but arrays are more preferred of course
you can use php eval() function like this:
eval("echo \$Q$c;");
but you should be careful not to put user data without validating, because it can lead to security issues.
I'm working with 3 different arrays (although I'm only testing with two for the time being) and I'm trying to process the arrays on $_POST. I'm currently using:
while(list($key_member,$member)=each($_POST['member_ids'])
&& list($key_amount,$amount)=each($_POST['payment_amounts']))
{
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
If I use one list() on either array it will print the info for that particular item. However, if I attempt to use multiple list() commands in the while, only the last list()ed item gets filled properly. Is list() doing some trickery in the background that's preventing it from working in a while loop?
Obviously the "easy" solution would be to use an index and simply force the issue, but I prefer enumerating -- and I'm honestly just curious as to
What am I doing wrong, and/or what is "broken" with list()?
bug? dunno.
here's a workaround.
while(list($key_member,$member)=each($_POST['member_ids'])){
list($key_amount,$amount)=each($_POST['payment_amounts']);
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
You could extract each array's keys using array_keys(), which produces an indexed array, then keep separate loop counters for each array:
$member_ids = array_keys($_POST['member_ids']);
$amounts = array_keys($_POST['payment_amounts']);
$mi = 0;
$am = 0;
while(1) {
...
$mi++
$am++;
if (count($member_ids) >= $mi) && (count(amounts) >= $am) {
break;
}
}
&& is evaluated in a short-circuit manner, the first statement to return false jumps out of it. In your case it stops to iterate as soon as the first array is at its end. list should work fine here, as it's a language construct which assigns variables.
I have this while loop.
while($show = $queryActivities->fetch()){ echo $show["name"]."<br>"; }
This takes data from the query and outputs the names..
Now is it possible to make a custom/fake data? I would like to make one if theres no data/statement in the $queryActivities then it should make a custom one called "name" with value "Nothing here.."
Is this possible? Can you do that?
I know I can do if($queryActivities->rowCount == 0){ echo "Nothing here" ; }
But I more thought of creating a custom data, so it runs the while loop, with the custom data, that only gets made if theres nothing in $queryActivities.
Something like..:
if($queryActivities->rowCount == 0){
# ..MAKE CUSTOM DATA..
# ..SOMETHING LIKE THIS MAYBE: ..
# $queryActivities = MAKE ARRAY WITH name => 'Nothing here'.. (just a thought)
}
while ($show = $queryActivities->fetch()){
echo $show["name"]."<br>";
}
Something like this, just what I imagine, although I dont know really how.
Thank you
Retrieve your data to an array, and then print it out. In between these two steps, you can modify it as desired.
This is more orderly, anyhow. I don't like retrieving from the DB and displaying in one step
You could either have an if/else that checks if the array is empty and prints a default message, or creates a default entry with a 'name' property that then is displayed with the same output loop as normal data. I'd prefer the first, but we'll do the second style since that's what you asked about.
Here's one simple solution.
$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }
if(empty($activities)){ $activities=array(array('name'=>'None Found')); }
foreach($activities as $activity){
echo $activity['name']."<br>";
}
I think just using an if/else is a better solution. Depending on your output style, though, this might involve more code repetition.
$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }
if(empty($activities)){
echo "None found <br>";
}
else{
foreach($activities as $activity){
echo $activity['name']."<br>";
}
}