array_intersect and match multiple values same time - php

In this script, you can see i try validate if 2 values - Jhon 34 -there are in the string called $values the same time, when i send the search i use 2 o 3 words and the idea it´s verification if find exactly this 3 or 2 words, etc, inside array
<?php
$values="Jhon,Smith,252546,34,house,car,phone";
$post="Jhon 34";
$exp_values=explode(",",$values);
$exp_post=explode(" ",$post);
$result=array_intersect($exp_post,$exp_values);
foreach ($result as $results) {
if(count($result)==count($exp_post)) {
echo $results;
print "<br>";
}
}
?>
I use count for show result only if the intersect elements it´s the same number as in the $post, because $post show values i want search inside $values, the result it´s ok if the same words find inside $values
The results it´s wrong because detect one word but i need detect all words i send, if array have all these words result must be ok, if haven´t this result it´s bad

You have the if and foreach backwards. First check if the count is the same to know that the post is valid, then show the results.
And instead of a loop, you can simply implode() $result:
if (count($result) == count($exp_post)) {
echo implode('<br>', $result);
} else {
echo "Invalid input";
}

Related

PHP Finding Data in Dynamic String

So, in short I have an issue I am facing where a bug in some code caused records to not be inserted into a database even though the UI told it that it was submitted (stupid checking on my part).
One thing we do though is log all the errors that are returned by the database so we can see any time a record isn't inserted and the reason why.
With this, I have all 7,200 records that need to be re-inserted into the database now that the issue has been fixed in the stored procedure.
This is how we stored the parameters that were being sent over:
xml=<data><optional><Account>1551573750449311384</Account></optional></data>, submitter=Q10004370, target=Q10224247, escalationType=aal, escalationReason=253, feedback= , preventable=1
I am going to loop over all of this data in my error log and try and prepare all of the data to re-insert back into the table. My issue is though that the string could contain less or more data; it's dynamic.
I need a way where I can search for the specific parts of the string such as xml or target.
That will allow me to set up all the data with the fields they need to be re-inserted into.
I first started with PHP's explode on the commas but realized that things are never in the same order. I then was going to try and use strpos to get the position and then get the value but had trouble doing so.
How can I go about getting the values (piece that precedes the = sign and is before the comma?
End Result is to be able to get each of the variables I need from this string so I can pass them to an insert statement to put them back into the database.
Update: While this is working, my issue now is that there could be commas in the feedback= section and its causing issues with the array.
$array = Array();
// Loop over each one of the records we are going to be working with
foreach($data->data as $p){
// Create an array of all the params
$pieces = explode(", ", rtrim($p->params, ", "));
// Debug to show all of the records we are using
/*
print '<pre>';
print_r($p);
print '</pre>';
*/
// Loop over all the params which is defined by the = sign
foreach($pieces as $item) {
// Put the values of each of the results into an array
$result[] = explode("=", trim($item));
}
// Loop over all of the results in the array
foreach($result as $item) {
// Store the param name as the key in our end result
$end[trim($item[0])] = $item[1];
}
// Push the final arrays into the results array
array_filter($end);
array_push($array, $end);
}
// Display the end results
print "<pre>";
print_r($array);
print "</pre>";
Maybe like this?
$str = 'xml=<data><optional><Account>1551573750449311384</Account></optional></data>, submitter=Q10004370, target=Q10224247, escalationType=aal, escalationReason=253, feedback= , preventable=1';
$foo = explode(",", $str);
foreach($foo as $item) {
$result[] = explode("=", $item);
}
foreach($result as $item) {
$end[$item[0]] = $item[1] ;
}
echo "<pre>";
print_r($end);
echo "</pre>";
Live link: http://sandbox.onlinephpfunctions.com/code/37aa046be2e9df37eff015ad292cd8a794a82782

Picking a random string from an array

Trying to get this code to work. It might be easier to show what I'm trying to do, and what is missing:
<?php
$array=array(
"something",
"something else"
);
/*pick a random entry in the array and store it as $output*/;
if(strpos($output,"else") !== false){
//do stuff;
}
echo "<div>";
echo $output
echo "</div>"
?>
As you can see, I'm having trouble trying to store a random entry in $output. What I want to do is to pick a random entry from the array, run a strpos on the result to do additional things if the conditions are met, and then output the same random entry between the divs.
EDIT: In case it's not clear, the line commented with /* and */ is supposed to be a 'fill in the blank' line, and not a 'this comment refers to the lines of code below' comment.
Use array_rand() to get a random entry.
$output = $array[array_rand($array)];
Generate a random number between zero and one less than the length of the array, use that as the array index to get a random item from the array.
<?php
$output = $array[rand(0, count($array)-1];

how to count number of records found in an array by in_array function?

I have an associative array $result_codes, I used in_array function to find if the provided zipcode is in array or not. Now I want to know how many zipcodes were found in array. and if there was no record then it should echo that no record found. Don't know how to do this because the loop runs before the if statement so else statement echo's message everytime when no record found in array.
if (bp_has_members)
while (bp_members()):
bp_the_member()
if ($zipcode != '')
if (in_array($zipcode, $result_codes)) { // some code here }
else {
echo 'sorry, no record found';
}
}
else {
// code runs if $zipcode is empty
}
endwhile;
endif;
This is very simple;
Lets say you have array
$array = array(1,1,1,2,2,3,3,3,3,4,4,5,5,5,5,);
use array_count_values($array) and you will get
$new_array = array(1=>3,2=>2,3=>4,4=>2,5=>4);
this array is a key value where the key is the value from the first array and the value is the number cells with this value;

Check if a specific word is in an array

I am having a a bit of an issue related to checking a returned array for specific matches.
Here is what I do:
I query a server API and the API returns a printable result using:
print_r($result);
the printed result is:
Array
(
[<html><center>Password_Saved!</center></html>] =>
)
So I thought I could do something like:
function checkResult ($needle, $haystack) { return ( stripos($haystack,$needle) !== false ? TRUE : FALSE); }
if ((checkResult("saved",$result))) {
echo "saved";
} else {
echo "not saved";
}
However, this does not work at all, so I am wondering if you could help me find a way if the $result contains the string saved since I need to know this to perform the next action based on the result.
Your help would be greatly appreciated.
The value you are looking for exists in the array's key instead of value.
As such, you need to be doing your search in the array's keys instead of values.
foreach ($result as $key => $value)
{
if (false !== stripos ($key, "saved"))
{
print "{$key} => Saved";
}
}
it doesn't work because your searching for saved when the value you have in the string is Saved. and you should pass your array key.
if ((checkResult("Saved",array_keys($result)[0]))) {
echo "saved";
} else {
echo "not saved";
}
Read about php preg_grep function
For example:
$needle_pattern = '/search/i'; // i for case insensitive
preg_grep($needle_pattern, $array_haystack);
Also notice that in your code you're mixing "saved" and "Saved" which are different :)
For further reading about this method:
How to search in an array with preg_match?
P.S If your "haystack" is actually the keys, you can switch $array_haystack with array_keys($array_haystack) to get an array of all keys.

For-Each Loop Misses First Index When Multiple Indices Exist

I've got the below PHP which works great when the array of locations only have 1 value, but when it has any number more than 1, the information on the first location keeps printing out blank. The array is set by calling explode on a comma-delimited list. When I set the array manually immediately before the loop, it works great! Yet not when I use explode, even though I printed the array and can confirm it's getting set up just as I expect (with the correct 0 index). The code I have is:
echo "<ul>";
foreach ($locations as &$value)
{
$locationDetails = mysql_query("SELECT id, name FROM locations WHERE id='$value'");
$locationDetailRow = mysql_fetch_assoc($locationDetails);
echo "<li>".$locationDetailRow['name']."</li>";
}
unset($value);
echo "</ul>";
I've confirmed that the query does not fail, that $value is what I expect it to be, and that the name does exist for the first $value in every case.
Any reason this should be failing on the first case when there are multiple locations?

Categories