array_intersect always evaluates to false - php

my code always goes into the "else-part", even if the "if-part" should be returned. When i delete the "else-part" it returns the "if-part".
foreach ($messageRepo as $oMessage) {
$messageTag = $oMessage->getMessageTags(); // get tags from all messages
$storeTagsUnseri = unserialize($messageTag); // unserialize tags given by the user
$storeTagsUnseri = (array)($storeTagsUnseri);
if (array_intersect($messageTagsArray,$storeTagsUnseri)) { //if tags from user matches tags from DB messages
$messageToTag[] = $oMessage->getMessageText(); // get the message text from the DB message and store it in array
$messageCrdate[] = $oMessage->getCrdate();
$allMessagesArray = array_flip(array_combine($messageToTag,$messageCrdate));
return $allMessagesArray;
} else {
$allMessagesArray[] = "flummi";
return $allMessagesArray;
}
}
This code always returns $allMessageArray 0 => "flummi" even if array_intersect is true.
Maybe if(array_intersect) is not possible at all? Is there another way to check if anything in one array matches in another array?
Thanks for your help!
EDIT
foreach ($messageRepo as $oMessage) {
$messageTag = $oMessage->getMessageTags(); // get tags from all messages
$storeTagsUnseri = unserialize($messageTag); // unserialize tags given by the user
$storeTagsUnseri = (array)($storeTagsUnseri);
if (array_intersect($messageTagsArray,$storeTagsUnseri)) { //if tags from user matches tags from DB messages
$messageToTag[] = $oMessage->getMessageText(); // get the message text from the DB message and store it in array
$messageCrdate[] = $oMessage->getCrdate();
$allMessagesArray = array_flip(array_combine($messageToTag,$messageCrdate));
}
}
if (!empty($allMessagesArray)) {
return $allMessagesArray;
} else {
return $allMessagesArray[] = "error";
}
}
This works now...but not very good coding i guess. ^^

Related

Comparison of words from the database and output of the result

I need to check the words received from the database with the user's entered word and if there is a match, then output its value from the database, and if not, then output what the user entered.
The code below works fine if there is a match.
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
}
}
}
}
I'm an amateur in PHP, just learning. And I can't figure out how to output $d_typeplace if no match is found.
I tried to add
else {
echo $d_typeplace;
}
, but I get an array of words from the user entered.
I will be grateful for any help. Also for any suggestions for improving this code.
---Addition---
I apologize for my English. This is a problem in the Russian language, I need to take into account the morphology. To do this, the database has a list of words and their analog, for example, X = Y. I get these words and compare what the user entered. If he entered X, then we output Y. If he led Z, which is not in the database, then we output Z.
Thus, we check $d_typeplace with $d_typeplace_raw and if there is a match, we output $d_typeplace_morf, which is equal to $d_typeplace_raw. And if not, then $d_typeplace (it contains the value that the user entered).
Oh, I'm sorry, I understand myself that I'm explaining stupidly)
I cannot quite understand what you are asking: you need to output the string entered by the user, but you can only print an array?
If this is the case, I think you parsed the string before, in order to therefore you need to do join again the values contained in the array.
Try with:
else {
echo implode(" ", $d_typeplace);
}
--- EDITED ---
Try with:
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
$found = false;
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
$found = true;
break;
}
}
if (!$found) {
echo $d_typeplace;
}
}
}
But I think it would be more efficient, if you implemented the second code snippet written by #Luke.T
I'm presuming you were trying to add the else like this?
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
} else {
echo $d_typeplace;
}
}
}
}
Which was outputting an array because the for loop was continuing, if you add a break like so...
echo $d_typeplace;
break;
It should stop outputting an array. Depending on your use case you could however perform similar functionality directly in your sql query using LIKE ...
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('
SELECT ego_slovoforma_v_predlozhnom_padezhe
FROM dEzpra_jet_cct_tip_mest_obrabotki
WHERE vozmozhnyi_variant_mesta LIKE %' . $d_typeplace . '%');
if ($typeplace_results) {
//Echo result
} else {
echo $d_typeplace;
}
}

PHP load XML and check for match

I have an XML file that I need to loop through and check for a string match. Not sure why the code below isn't working, i.e. does not return "true".
XML
<AUTHORIZED>
<USER>janedoe</USER>
<USER>sallysmith</USER>
<USER>walterwilliams</USER>
<USER>jennyjones</USER>
</AUTHORIZED>
PHP
<?php
$user = 'janedoe';
//Load xml file
if (file_exists('users.xml')) {
$authUsers = simplexml_load_file('users.xml');
} else {
echo 'Could not find list of authorized users!';
}
//Check for approved user
if(in_array($user, $authUsers)){
$approvedUser = 'true';
} else {
$approvedUser = 'false';
}
echo $approvedUser;
?>
The function simplexml_load_file returns a SimpleXMLElement and not an Array, so you can't use the in_array function to do this.
What you can do, is take the value if $authUsers->USER (which is also a SimpleXMLElement), convert it to array, and then check it:
$str = "<AUTHORIZED>
<USER>janedoe</USER>
<USER>sallysmith</USER>
<USER>walterwilliams</USER>
<USER>jennyjones</USER>
</AUTHORIZED>";
$user = 'janedoe';
$authUsers = simplexml_load_string($str);
var_dump((array) $authUsers->USER);
//Check for approved user
if(in_array($user, (array) $authUsers->USER)){
$approvedUser = 'true';
} else {
$approvedUser = 'false';
}

Passing array of data to other page using session in PHP

I have some problem passing array of data in Php using session:
In my class, I have this function:
public function check_dupID($id)
{
$this->stmt="select id from student where id='$id'";
$this->res = mysql_query($this->stmt);
$this->num_rows = mysql_num_rows($this->res);
if($this->num_rows == 1)
{
while($this->row = mysql_fetch_array($this->res))
{
$dup_id = $this->row[0];
return $dup_id;
}
}
}
This code checks for duplicate ID of a student. Now, the reason for this is that I uploaded the file in the database using ".csv" file.
Before Uploading it I put all the data in the csv file into an array. Now, I check it one by one:
//created the variable for checking
$id = $check->check_dupID($array[0]);
if($id == TRUE)
{
session_start();
$_SESSION['id']; = $id;//passing it to the next back to array again.
$redirect->page($error);
}
Now when it redirect it gives me the result of an "Array" and if I parse it using foreach it shows only one id but there is more than of that. I want to know how to display it all.
This code will return the duplicate id when it is found for the first time. If you want to return all the duplicate ids, then add them into an array using the while loop and then return it.
To do this modify your code like this:
public function check_dupID($id)
{
$this->stmt="select id from student where id='$id'";
$this->res = mysql_query($this->stmt);
$this->num_rows = mysql_num_rows($this->res);
$dup_id = array();// added here to prevent invalid argument supplied to foreach loop error if nothing is found
if($this->num_rows >1)
{
while($this->row = mysql_fetch_array($this->res))
{
$dup_id[] = $this->row[0];// adding duplicates into the array
}
return $dup_id;
}
}
This code fixes my problem:
if($id == TRUE)
{
$get_id = array();
$get_id[] = $id;
session_start();
$_SESSION['id']; = $get_id;//passing it to the next back to array again.
$redirect->page($error);
}

Check if the fetched array is empty or not PHP?

I am trying to check if the mysql_fetch_array() function returns an empty array or not. But my code doesn't seem to work. Here I want to ensure that if the array is empty I want to display under construction message.
Code :
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
while($fetchSet = mysql_fetch_array($exeQuery)) {
if(count($fetchSet) == 0) {
echo "This Page is Under Construction";
}else{
// something else to display the content
}
}
How do I check to acheive such feature ?
use mysql_num_rows to count number of rows. try this.
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery)== 0){
echo "This Page is Under Construction";
}
else{
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
}
You really should be using mysql_num_rows http://us2.php.net/manual/en/function.mysql-num-rows.php
However, on a side note, you should use php empty() instead. http://us2.php.net/empty
When you use mysql_fetch_array(), it returns the rows from the data
set one by one as you use the while loop.
If there will be no record, while loop wont execute. In this case, declare a boolean variable and make it true if it enters the while loop. Like:
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
$recordExists = 0;
while($fetchSet = mysql_fetch_array($exeQuery)) {
if($recordExists == 0 )
$recordExists = 1;
// something else to display the content
}
if($recordExists == 0 ){
echo "This Page is Under Construction";
}
Hope this works!
You can do it this way:
while($r[]=mysql_fetch_array($sql));
// now $r has all the results
if(empty($r)){
// do something
}
source: php doc
Your code inside the while loop never runs if there are no results. mysql_fetch_array returns null/false if there are no more results. What you need yo do is check with mysql_num_rows first, before the while.
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows ($exeQuery) == 0) {
echo "This Page is Under Construction";
}
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
Try this
if(empty($fetchSet)
{
echo "This Page is Under Construction";
}
else
{
// something else to display the content
}

(PHP) Reject descriptions that don't include the required tags

This is how my script currently sends errors when the description is too short:
if(strlen($linkres->content) = minStoryLength ) { // if description is too short
$main_smarty->assign('submit_error', 'incomplete');
$main_smarty->display($the_template . '/submit_errors.tpl');
$error = true;
}
I want to send the same error message when the description does not include at least one of these tags/words:
<img><youtube><googlevideo><xoinks><break><vimeo><revver><myspace>
<veoh><wmv><dailymotion><ifilm><metacafe><tubeley><guba>
thanks for your help!
I would use some regex here, to do a negative match
$tags = array("img", "youtube", "googlevideo", "xoinks", "break", "vimeo", "revver", "myspace", "veoh", "wmv", "dailymotion", "ifilm", "metacafe", "tubeley", "guba");
if ((strlen($linkres->content) < minStoryLength) // if description is too short
|| (!preg_match("'[<](".implode("|",$tags).")[^>]*[>]'is",$linkres->content)))
// or it does not contain any of the above
{
$main_smarty->assign('submit_error', 'incomplete');
$main_smarty->display($the_template . '/submit_errors.tpl');
$error = true;
}
EDIT: made a little correction
EDIT2: I had a missing parameter for preg_match
$tags = array('img','youtube','googlevideo','xoinks','break','vimeo','revver','myspace','veoh','wmv','dailymotion','ifilm','metacafe','tubeley','guba');
$contains = false;
foreach($tags as $check)
{
if(preg_match("/<".$check.">/", $linkres->content))
{
$contains = true;
}
}
if(!$contains)
{
// here goes your error
}
This is an alternative to inti's solution.
1 Insert your tags in an array
2 Iterate the array and check if the value is matching
foreach()
http://www.php.net/manual/en/control-structures.foreach.php
3 Show error

Categories