coding to check the data with array Intersect - php

I wanted to check to enter data into the database.Checks are as follows
$implode1 = "cat, dog, chicken";
$implode2 = "cow, goat, cat";
If the cat in the variable $implode1 is also contained in the variable $implode2, it should display a warning message. How to code for the above problem?
Help me please :(

You could explode your strings to arrays, then use array_intersect to return the values which are present in both, eg:
$string1 = 'cat, dog, chicken';
$string2 = 'cow, goat, cat';
$compare = explode(', ', $string1);
$against = explode(', ', $string2);
$matches = array_intersect($compare, $against);

$implode1 = "cat, dog, chicken";
$implode2 = "cow, goat, cat";
$imp1 = explode(', ',$implode1);
$imp2 = explode(', ',$implode2);
foreach($imp1 as $val){
if(in_array($val,$imp2)) {
echo "$val is present in $implode2";
}
}

loop the first array and check if any element is present in the second - something like this:
foreach($implode1 as $val){
if(in_array($val,$implode2)) {
echo "$val is exists in the implode2 array";
}
}
ohh, sorry, those are just strings. First explode them:
arr_implode1 = explode(", ",$implode1)
arr_implode1 = explode(", ",$implode2)

You could just check before inserting the values into a database if they already exist:
if not exists (select * from TestTable where column NOT IN {$implode})
begin
...Do something here!!
end

Create yourself a function that is able to extract the values out of each string in form of an array, then get the intersection. If it is not FALSE, there is an intersection, so do the warning:
$values = function($string) {
return explode(', ', $string);
};
if (array_intersect($values($implode1), $values($implode2))) {
trigger_error('Values intersect', E_USER_WARNING);
}
See it in action.

Related

Saving values from a variable to an array

I have a long string variable that contains coordinates
I want to keep each coordinate in a separate cell in the array according to Lat and Lon..
For example. The following string:
string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
I want this:
arrayX[0] = "33.110029967689556";
arrayX[1] = "33.093492845160036";
arrayX[2] = "33.0916232355565";
arrayY[0] = "35.60865999564635";
arrayY[1] = "35.63955904349791";
arrayY[2] = "35.602995170206896";
Does anyone have an idea ?
Thanks
Use substr to modify sub string, it allow you to do that with a little line of code.
$array_temp = explode('),', $string);
$arrayX = [];
$arrayY = [];
foreach($array_temp as $at)
{
$at = substr($at, 1);
list($arrayX[], $arrayY[]) = explode(',', $at);
}
print_r($arrayX);
print_r($arrayY);
The simplest way is probably to use a regex to match each tuple:
Each number is a combination of digits and .: the regex [\d\.]+ matches that;
Each coordinate has the following format: (, number, ,, space, number,). The regex is \([\d\.]+,\s*[\d\.]+\).
Then you can capture each number by using parenthesis: \(([\d\.]+),\s*([\d\.]+)\). This will produce to capturing groups: the first will contain the X coordinate and the second the Y.
This regex can be used with the method preg_match_all.
<?php
$string = '(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)';
preg_match_all('/\(([\d\.]+)\s*,\s*([\d\.]+)\)/', $string, $matches);
$arrayX = $matches['1'];
$arrayY = $matches['2'];
var_dump($arrayX);
var_dump($arrayY);
For a live example see http://sandbox.onlinephpfunctions.com/code/082e8454486dc568a6557058fef68d6f10c8dbd0
My suggestion, working example here: https://3v4l.org/W99Uu
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
// Split by each X/Y pair
$array = explode("), ", $string);
// Init result arrays
$arrayX = array();
$arrayY = array();
foreach($array as $pair) {
// Remove parentheses
$pair = str_replace('(', '', $pair);
$pair = str_replace(')', '', $pair);
// Split into two strings
$arrPair = explode(", ", $pair);
// Add the strings to the result arrays
$arrayX[] = $arrPair[0];
$arrayY[] = $arrPair[1];
}
You need first to split the string into an array. Then you clean the value to get only the numbers. Finally, you put the new value into the new array.
<?php
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
$loca = explode(", ", $string);
$arr_x = array();
$arr_y = array();
$i = 1;
foreach($loca as $index => $value){
$i++;
if ($i % 2 == 0) {
$arr_x[] = preg_replace('/[^0-9.]/', '', $value);
}else{
$arr_y[] = preg_replace('/[^0-9.]/', '', $value);
}
}
print_r($arr_x);
print_r($arr_y);
You can test it here :
http://sandbox.onlinephpfunctions.com/code/4bf04e7aabeba15ecfa114d8951eb771610a43a4

How do I concatenate each the values of a variable1 with each values of variable2

// a simpler thing that would get me what I need is:
How do I concatenate each the values of a variable1 with each values of variable2
$Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are symbols
$Var2 = 'word1, word2, word3'; // here also dozens of entries, are words.
How do I have all the keys of a variable, placed together of the keys of another variable?
$Values_that_I_needed = 'my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3';
How would I build this values this variable up with all those values without having to type everything!?
Imagine an example with 60 my1, my2 … and 130 word1, word2 …. it’s my case!
Put each of the 60my before each of the 130 words !!
// I need to concatenate / join / join each values / keys of a variable, with all the values/keys of another variable, to avoid making all these combinations by hand. and put in another variable.
The solution using explode and trim functions:
$Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are symbols
$Var2 = 'word1, word2, word3';
$result = "";
$var2_list = explode(',', $Var2);
foreach (explode(',', $Var1) as $w1) {
foreach ($var2_list as $w2) {
$result .= trim($w1) . trim($w2). ', ';
}
}
$result = trim($result, ', ');
print_r($result);
The output:
my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3
Below cod should work if var1 and var2 have the same length
<?php
$tab1=explode(',',$var1);
$tab2=explode(',',$var2);
$c=$count($tab1);
$output='';
for($i=0;$i<$c;$i++){
$output.=$tab1[$i].$tab2[$i].', ';
}
echo $output;
$Var1 = 'my1, my2, my3';
$Var2 = 'word1, word2, word3';
$Array1 = explode(", ",$Var1); // create array from $Var1
$Array2 = explode(", ",$Var2); // create array from $Var2
foreach($Array1 as $My){
foreach($Array2 as $Word){
$Result[] = $My.$Word; // Join Var1 & Var2
}
}
$Values_that_I_needed = implode(", ", $Result);
echo $Values_that_I_needed; // my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3

How to perform an action on each imploded value?

I do not have a real use case but am simply wondering if this is possible and how i should do it.
Let's say I have the following array:
$array = array('1234', '5678', '9101', '1121', '3141');
And I would like to implode that.
$string = implode(',', $array);
Let's say I would like to perform an action on the values before they get implodes. For example reversing the string using strrev(). How would I go about this?
Edit
I will try to explain it a little better.
$array = range('a', 'z');
// I know this is not possible
$string = implode(', ', strtoupper($array));
// Desired output : A, B, C, D ...
I am wondering if it can be done using array_map() but ain't good in working with that function.
array_map function should work fine for built-in and "custom" functions(as a first argument of the function):
$array = array('1234', '5678', '9101', '1121', '3141');
$string = implode(', ', array_map("strrev", $array));
print_r($string); // "4321, 8765, 1019, 1211, 1413"
Another approach:
function addSeparator($word, $char = "-") {
$words = str_split($word, 2);
return implode($char, $words);
}
$string = implode(', ', array_map("addSeparator", $array));
print_r($string); // "12-34, 56-78, 91-01, 11-21, 31-41"
Simply do your logic before imploding:
$array = array('1234', '5678', '9101', '1121', '3141');
foreach ($array as &$value) {
$value = strrev($value);
}
$string = implode(',', $array);

LIKE to search for first three characters of each comma separated value

In a string,
$string_example = "cats, dogs, horses"
I'd like to get
$string_truncated = "cat, dog, hor"
i.e. getting the first three characters of each comma separated value
Later, I will use this in an SQL LIKE statement to restrict search results that match at least the first three characters given (I can't do FULL TEXT because I want to keep my foreign key constraints and can't give up my DB engine)
$string_example = "cats, dogs, horses";
$arr = explode(',',$string_example);
$newArr = array();
foreach($arr as $val){
if($val != ''){
$newArr[] = substr(trim($val),0,3);
}
}
$newStr = implode(', ',$newArr);
echo $newStr;
You can do:
<?php
$string_example = "cats, dogs, horses";
$arr = explode(",", $string_example);
$newArr = array();
foreach($arr as $value) $newArr[] = substr(trim($value), 0, 3);
$newString = implode($newArr,", ");
echo $newString;
?>
Output:
cat, dog, hor
Using array_map, substr, explode and implode:
$string_example = "cats, dogs, horses"
$truncated_ary = array_map(
function($search_string){
return substr($search_string, 0, 3)
},
explode(',', $string_example)
);
$string_truncated = implode(',', $truncated_ary);
$string_example = "cats, dogs, horses";
$words = explode(',',$string_example);
$result = array();
foreach($words as $val){
if($val != ''){
$result[] = substr(trim($val),0,3);
}
}
$newStr = implode(', ',$result);
echo $newStr;

PHP compare two arrays from different locations

I am wanting to compare two different arrays. Basically I have a database with phrases in and on my website I have a search function where the user types in a phrase.
When they click search I have a PHP page which 'explodes' the string typed in by the user and its put into an array.
Then I pull all the phrases from my database where I have also used the 'explode' function and split all the words into an array.
I now want to compare all the arrays to find close matches with 3 or more words matching each phrase.
How do I do this?
Well what I've tried totally failed, but here is what I have
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //user entered data
$search_term = str_replace ("?", "", $search_term); //removes question marks
$array = explode(" ", $search_term); //breaks apart user entered data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array) . " LIMIT 0,10";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title'];
$thetitle = str_replace ("?", "", $thetitle);
$title_array[] = $thetitle;
$newarray = explode(" ", $search_term);
foreach ($newarray as $key=>$newword) {
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value);
$contacts = array_diff_key($thenewarray, array_flip($newarray));
foreach($contacts as $key => $value) {
echo $newword."<br />";
echo $value."<br /><hr />";
}
}
}
But basically all I want is to display suggested phrases which are similar to what the user has already typed into the search box.
So If I searched "How do I compare two arrays that have the same values?", I would see 10 suggestions that are worded similar, so like "How to compare multiple arrays?" or "can I compare two arrays" etc...
So basically like when I first posted this question on this site, I got other questions that may help, thats basically what I want. This code im using was origionally to match just one word or an exact matching string, im editing it to find matching words and only show phrases with 3 or more matching words.
I don't think that this is the best solution for your search script. But I'll try to give you the answer:
<?php
$string1 = "This is my first string";
$string2 = "And here is my second string";
$array1 = explode(" ", $string1);
$array2 = explode(" ", $string2);
$num = 0;
foreach($array1 as $arr) {
if(in_array($arr, $array2))
$num++;
}
$match = $num >= 3 ? true : false;
?>
use array_intersect function
$firstArray = "This is a test only";
$secondArray = "This is test";
$array1 = explode(" ", $firstArray);
$array2 = explode(" ", $secondArray);
$result = array_intersect($array1, $array2);
$noOfWordMatch = count($result);
$check = $noOfWordMatch >= 3 ? true : false; ;

Categories