how coding to check the data with array Intersect? - php

I wanted to check to enter data into the database.Checks are as follows
$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";
If the banana in the variable $implode1 is also contained in the variable $implode2, it should display a warning message.
and if the value of the variable is empty, then the execution will be ignored. example:
$implode1 = "";
$implode2 = "";
How to code for the above problem?
Help me please :(

$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";
$implode1Array = explode(", ", $implode1);
$implode2Array = explode(", ", $implode2);
$result = array_intersect($implode1Array, $implode2Array);
if(count($result) > 0) {
exit('Error!');
}

Typically I would assume that by cat you mean concatenation, but it doesn't seem proper here. But, assuming that is what you mean, you would just check for the same concatenation character (a comma) in both variables, like so:
if ( stristr($implode1, ",") && stristr($implode2, ",") ) {
// error
} else {
// success, do something
}
However, assuming you mean the same item being entered in both variables, in this case fruit, you can check it this way:
$im1 = explode(",", $implode1);
$im2 = explode(",", $implode2);
foreach($im1 as $i) {
if ( array_search($i, $im2) ) {
// error
} else {
// success, do something
}
}
You could of course just search both strings for a given value, but I don't think that's what you're going for. But assuming it is, here is that code:
$duplicate = "apple"; // the item you are searching for a duplicate of
if ( stristri($implode1, $duplicate) && stristr($implode2, $duplicate) ) {
// error
} else {
// success, do something
}

if (count(array_intersect)) { /* warning */ }

You can use PHP's array_intersect function to get the intersection (see http://php.net/manual/en/function.array-intersect.php):
$arr1 = explode(", ", "apple, orange, banana");
$arr2 = explode(", ", "banana, mango");
$intersection = array_intersect($arr1, $arr2);
if (count($intersection) > 0) {
echo "WARNING: the lists have a non-empty intersection!";
}

Related

PHP strpos() and str_replace()

I got a problem with my small php script.
My code should function as a follow-/unfollow-system like in forum softwares (for example XenForo).
So what my script does is that it searches for a user in a string and if the name is found it removes the name of the user in the string. But my problem is that the script can not search for the name and comma for some reason because I try to remove the comma from the string aswell.
Any help is appreciated, thanks in advance :)
Example:
Peter is following Franz and George but he want's to unfollow George
Script:
<?php
$user1 = "Peter";
$following1 = "Franz, George";
$user2 = "Franz";
$following2 = "Peter, George";
$user3 = "George";
$following3 = "Peter, Franz";
//
//
//
if (strpos($following1, $user3) == true) {
echo "Can remove follow.";
if (strpos($following1, ", $user3")) {
$user3 = ", $user3";
$fNew = str_replace($user3, "", $following1);
echo "$fNew<br>";
} else if (strpos($following1, "$user3, ")) {
$use3 = "$user3, ";
$fNew = str_replace("$user3", "", $following1);
echo "$fNew<br>";
}
} else if ($following1 == $user3) {
echo "Can remove follow.";
$fNew = str_replace($user3, "", $following1);
echo "$fNew<br>";
} else {
echo "Can't remove follow";
}
?>
Have a look a this:
<?php
$follow = "Peter, Franz, Spongebob";
$guyToUnfollow = 'Franz';
$people = explode(',', $follow);
var_dump($people);
foreach ($people as $key => $person) {
$person = trim($person);
if ($person == $guyToUnfollow) {
unset($people[$key]);
}
}
$follow = implode(',',$people);
var_dump($follow);
Firstly, we convert the CSV to an array, then loop through it. We use trim to remove whitespace, and unset any value in the array that matches the guy you want to unfollow. Finally, we recreate the csv using implode.
See it working here https://3v4l.org/QEnHj
strpos returns the position of the string, so you need to check if its not false in stead of checking if its true.
So you should use:
strpos($following1, $user3) !== false

Comparing dynamic arrays together with an if then else statement

In my code I want to replace the following:
if($file['domain']=="VALUE" || $file['domain']=="VALUE" || $file['domain']=="VALUE" || $file['domain']=="VALUE"){}
else{}
with something like this that can be changed in a more generic config file:
$domains_to_exclude="VALUE,VALUE,VALUE,VALUE";
The values of both arrays change and vary. What I want to do is if the $file['domain'] matches the value of domains_to_exclude is to skip over it.
I am going in the right direction by trying something like this. So far I've not had any success.
$myArray = explode(',', $domains_to_exclude);
$count = count($file);
for ($i=1; $i<$count; $i++)
{
if ($myArray[$i] !== $file['domain'])
{
$domain=$file['domain'];
$domainn = str_replace("", "", $domain);
echo'<option value="'.$domain.'">'.$domainn.'</option>';
}
else {}
}
$myArray = explode(',', $domains_to_exclude);
if (!in_array($file['domain'], $myArray)) {
// Domain is ok, process file
}
in_array($str, $arr) checks if any of the values in $arr equals $str.
And also, you don't have to have that else block there if it is empty. But it won't affect your code negatively either.
you can do something like this:
$domains_to_exclude = array(...); //make an array of your "VALUES"
$file = array('foo', 'bar'); // your $file array
if(count(array_intersect($domains_to_exclude, $file)) > 0){
// at least a match was found
}

in_array() keeps appending values if looping through db rows

I need to identify every instance where a value in one array (needle) occurs in another array (haystack). in_array() seems to be my best option, and the code below works perfectly until I need to use it on rows fetched from a db - it keeps appending values instead of setting them each time it's called.
While I can't actually use unset() in this situation, I was surprised to discover that even that didn't seem to resolve the problem.
UPDATE - Example of what's being returned
I temporarily changed the db values so that $needles has only value per row (in order to make it possible to sort through the values filling up my screen ;-))
False;
False; False; True;
False; False; True; False; True;
False; False; True; False; True; False; True;
False; False; True; False; True; False; True; False;
This works correctly
(I've posted a functional example here)
$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');
foreach ($needles as $needle) {
if (in_array($needle, $haystack) ) {
$Match = 'True';
}
else {
$Match = 'False';
}
}
This keeps appending values - Edited to reflect the code I'm using
$Customer_Categories_Arr = array('Casual','Trendy');
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$Product_Categories_Arr[]=$row["Taste_Category"];
// Use when column contains CSV
// $Product_Categories_Arrx = explode(',', trim($Product_Categories_Arr[0]));
foreach ($Product_Categories_Arr as $Product_Category_Arr) {
if (in_array($Product_Category_Arr, $Customer_Categories_Arr)){
$Matches_Product_Category = "True";
} else {
$Matches_Product_Category = "False";
}
echo $Product_Category_Arr, ', ', $Matches_Product_Category, '; ';
}
}
}
It is not really clear what you are trying to do. But maybe this would help:
$customerCategories = array('Casual', 'Trendy');
if( $stmt->columnCount() ){
while( $row = $stmt->fetch( PDO::FETCH_ASSOC )){
$productCategoryRow = $row[ 'Taste_Category' ];
// If it is not working, try uncommenting the next line
// $productCategories = [];
$productCategories = explode( ',', trim( $productCategoryRow ));
$match = "False";
foreach( $productCategories as $productCategory ){
if( in_array( $productCategory, $customerCategories )){
$match = "True";
}
echo $match . ";";
}
}
}
This prints your result on the screen every time a loop is done. Is this what you mean?
If you want the second block of code to do what the first block of code (which works correctly) does, then the second block should look like this -
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$needle =$row["product_var"];
$Match = "False";
if (in_array($needle, $haystack)){
$Match = "True";
}
}
}
You don't need do use the foreach because that is replaced by the while loop in the second block.
I am going to try an solve this. I think the problem is with:
$needles[]=$row["product_var"];
I think this should be:
$needles=$row["product_var"];
The column "product_var" contains an CSV (as you mentioned), so I can make an example like this:
$csv = "jake;john;alex;kim";
An example with brackets ($needles[]):
for($i=0; $i<5; $i++) {
$needles[] = explode(";", $csv);
echo(count($needles).", ");
}
returns:
1, 2, 3, 4, 5,
edit (for more explaining):
if I use print_r I see the array expanding, exactly how it happens in your example:
step 1: it adds an array to $needles with values ('jake','john','alex','kim')
step 2: it adds an array to $needles, so it contains 2x the values ('jake','john','alex','kim')
step 3: it adds an array to $needles, so it contains 3x the values ('jake','john','alex','kim')
etc.
Now without the brackets ($needles):
for($i=0; $i<5; $i++) {
$needles = explode(";", $csv);
echo(count($needles).", ");
}
This returns:
4, 4, 4, 4, 4,
And every time the array simply contains the values ('jake','john','alex','kim') -which is what you want.
Could this explain the "expanding values"? (or am I just doing something really stupid which has nothing to do with your problem??)
edit:
If this is what is going wrong, then you are adding to an array, instead of only using the new array from $row["product_var"] (hope this makes any sense; it seems I am pretty bad at explaining what's happening).

Ignore certain value and add comma into it

I would like to add comma to each value output, example: A, B, C. Also I would like to ignore certain value by not output it.
Here is my code:
$result2 = ldap_search($ldapconn, "ou=group,dc=fake,dc=com", "memberuid=*$username*");
$entry1 = ldap_get_entries($ldapconn, $result2);
?>
</td>
<td>
<?php
$temp_array = array();
for ($i=0;$i<sizeof($entry1);$i++) {
if (isset($entry1[$i]['cn'][0])) {
if (strlen(trim($entry1[$i]['cn'][0]))!=0) {
array_push($temp_array, $entry1[$i]['cn'][0]);
}
}
}
$usergroup = implode(',', $temp_array);
$usergroups = explode(",", $usergroup);
foreach($usergroups as $x=>$x_value) {
switch ($x_value) {
case "management":
case "Team Leaders":
case "superuser":
$x_value = "";
break;
}
echo $x_value;
}
So the expected result should be like this without showing the above 3 values in the switch case,
User A - IT, Marketing
Ignoring the the values above if User A has the values.
As I mentioned in the comments, if you have an array, doing implode and then explode using the same delimiter achieves absolutely nothing. In your case $usergroups will be exactly the same as $temp_array.
You can greatly simplify your code like this:
// This is just an example using what I think your array contains
$temp_array = array('IT','management','superuser','Marketing');
// Write a list of words to ignore
$ignores = array("management", "Team Leaders", "superuser");
// Loop over your array and remove the entries that contain the ignored words
foreach ($temp_array as $key => $value) {
if (in_array($value, $ignores)) {
unset($temp_array[$key]);
}
}
echo implode(',', $temp_array); // outputs: IT,Marketing

if explodable / else

I have a string which may or may not contain commas. If it does, I want it exploded into an array; if it doesn't, I still want the string saved to the new identifier. My code clearly doesn't work. Anyone have any better ideas?
if(explode(",", $_SESSION['shoparea']))
{
$areas = explode(",", $_SESSION['shoparea']);
} else {
$areas = $_SESSION['shoparea'];
}
What is the correct syntax for this operation?
if(strpos($_SESSION['shoparea'], ',') !== false) {
$areas = explode(',', $_SESSION['shoparea']);
} else {
$areas = $_SESSION['shoparea'];
}
Everything can be exploded, if there are no instances of the delimiter it becomes a singleton array, so it may be simpler to do
$result = explode(",", $_SESSION['shoparea']);
if (count($result) == 1)
$areas = $result[0];
else
$areas = $result;
You could use http://php.net/strpos function to ensure that ',' are present.
you could do this for examle
$areas = $_SESSION['shoparea'];
if(strpos($areas, ',') !== false) {
$areas = explode(",", $areas);
}
All you need is
$_SESSION['shoparea'] = "xx"; // Test value ..
if (!$areas = explode(",", $_SESSION['shoparea'])) {
$areas = array($_SESSION['shoparea']);
}
Output
array
0 => string 'xx' (length=2)
Note : $areas needs to always be array .. if you are using a loop you might have issue so i converted it ..
if (substr_count($_SESSION['shoparea'], ',') > 0) {
$areas = explode(",", $_SESSION['shoparea']);
}
else {
$areas = $_SESSION['shoparea'];
}

Categories