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.
Related
I would like to unset an HTTP Posted key from the array after it echoes the "1" result, but the unset doesn't seem to work. How can I fix this?
$keylist = array('HHH', 'GGG');
if (in_array($_POST["keys"], $keylist)){
echo "1";
unset($keylist[$_POST["keys"]]);
} else {
echo "0" ;
}
Appreciate any help,
Hobbyist
Your unsetting $keylist not $_POST
unset($_POST["keys"]);
You're using the wrong array key for unsetting (You're trying to unset $keylist["HHH"], not, say, $keylist[0]) - you'll need to retrieve the key from the array, and then unset that specifically in order to remove it from the keylist.
$index = array_search($_POST["keys"], $keylist);
if($index!==false) { //YES, NOT DOUBLE EQUALS
unset($keylist[$index));
}
If $_POST["keys"] is an array of keys, you'll need to use array_keys with a search_value instead.
Array_search documentation: http://php.net/manual/en/function.array-search.php
Array_keys documentation: http://php.net/manual/en/function.array-keys.php
EDIT: Adding a full, working example.
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
if(in_array($_POST["keys"], $keylist)) {
$indexToRemove = array_search($_POST["keys"], $keylist);
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Another example, this time checking the index itself to see if it is not false:
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
$indexToRemove = array_search($_POST["keys"], $keylist);
if($indexToRemove!==false) {
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Output:
1Array ( [0] => asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh [1] => derp2 ) Array ( [1] => derp2 )
I realize now that I only had one = on the $index!==false check - the reason you need two is because $index is 0 if you're removing the first element of an array. Per PHP documentation,
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE. Please read the section on Booleans for more
information. Use the === operator for testing the return value of this function.
in_array($_POST["keys"], $keylist) checks if the posted value $_POST["keys"] is present as a value in $keylist, but unset($keylist[$_POST["keys"]]) uses $_POST["keys"] as the key in $keylist to unset something.
Since in_array() returns true, the posted value is present in the array $keylist. But you can't do unset($keylist['GGG']) because that value is not set.
A simple solution is to use the same values as keys too:
$keylist = array('HHH', 'GGG');
$keylist = array_combine($keylist, $keylist);
More about array_combine().
Your array have keys. So "HHH" in keylist is $keylist[0] and not $keylist['HHH']. You can not unset it because you have to define the array key instead of the array value.
Try to search for the array value like this:
array_search($_POST["keys"], $keylist)
This will return the array key for you or false if its not found. Your full code should like look like:
echo "1";
$arrkey = array_search($_POST["keys"], $keylist);
if( $arrkey !== false ){
unset($keylist[$arrkey]);
}
Here the PHP Manual for the array_search function: http://php.net/manual/en/function.array-search.php
I'm trying to find a way to check if the value of a given key exists in an array (inside a foreach loop).
For some reason it doesn't really work as expected.
The idea is that I already know the name of the key, but only know part of the correlating value for the key.
I'm trying to do something like this, assuming that I know the key is "exampleKeyName" and its value may or may-not contain "matchValue":
foreach( $array as $key => $value) {
if (stripos($array["exampleKeyName"], 'matchValue') !== false) { echo "matched"; }
}
This returns "illegal string offset".
However, if I do this it works:
foreach( $array as $key => $value) {
if (stripos($value, 'matchValue') !== false) { echo "matched"; }
}
The problem here is that I want to be more specific with the query, and only check if the key is "exampleKeyName".
You can use stripos to check the array value contains in a matching string like this way:
foreach( $array as $key => $value) {
if (stripos($array[$key], 'matchValue') !== false) { echo "matched"; }
}
If you want to check if your regex pattern matches a specific value in your array :
if(preg_match("/^yourpattern$/",$myArray["exampleKeyName"])>0) {
// The value of $myArray["exampleKeyName"] is matched by the regex
}
If you check if the regex matches a key :
foreach($myArray as $key => $value):
if(preg_match("/^yourpattern$/",$key)>0) {
// $key is matched by the regex
}
endforeach;
I hope it helps !
edit : bad english
You're not far off, and there are a few ways of doing this.
In your example code you weren't checking the key but the value in both cases. When doing a for loop like in your second code example you have to change your if statement like so to check against the key:
if (stripos($key, 'matchValue') !== false) { echo "matched"; }
Since I don't know what the application of this is I'll just tell you a few other ways of achieving this and perhaps they will also help simplify the code.
php has a helper function called array_key_exists that checks if the given key or index exists in the array. The result is a boolean value. If you just need to know if the array contains an index or key that is another way of doing this. That would look like this:
if( array_key_exists('matchValue', $array) ) {
print('Key exists');
} else {
print('No key found');
}
There is a good Stack Overflow posting about using preg_grep for regex searching of array keys that may also be helpful if you need to use regular expressions for this.
I have a piece of code where the condition fails even when the array is empty.
This is the code:
echo "<pre>";
print_r($_FILES['jform']['name']['gallery']);
which outputs
Array
(
[0] =>
)
This is the condition:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile))
{
//do something
}
It should fail, but the program enters the if block. Why?
As you can see from the print_r() the array is NOT empty - it has one element, which on the other side looks like white space or empty.
Update
I would recommend reading POST method uploads, where you'll learn that name is the original name of the file and tmp_name is a random name of the temporary file, that has been just uploaded.
According to my experience you should check the Error Messages.
The check you're interested is:
foreach ( array_keys( $_FILES['jform']['gallery'] ) AS $key ) {
if ( UPLOAD_ERR_OK == $_FILES['jform']['gallery']['error'][$key] ) {
// do the stuff with the uploaded file in $_FILES['jform']['gallery']['tmp_name'][$key]
}
}
Keep an eye on the names of the arrays where gallery is before name.
As you can see your array is not empty it has a blank element.
The work around is array_filter which will eliminate blank data
$array = array(0=>'');
$array1 = array_filter($array);
print_r($array1);
if(!empty($array1)){
echo "has elememt";
}else{
echo "empty";
}
This is what u need
UPDATE
What if the value contains multiple spaces, yes this could be handled using a call back function
$array1 = array_filter($array,"call_back_function");
function call_back_function($val){
return trim($val);
}
In your case print_r() told you that galfile == array('') // 1 element is in the array
According to the documentaion only array() // 0 elements is considered empty. So the if statement is executed correctly.
In your case you should write:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile) && !empty($galfile[0]) )
{
//do something
}
When you working with arrays, before checking for empty you can sanitize your array using array_filter or the similar functions:
$galfile = array_filter($_FILES['jform']['name']['gallery']);
if(!empty($galfile))
{
//do something
}
But when you use global array _FILES, more correctly is checks for error:
if($_FILES['jform']['error']['gallery'] == 0)
{
//do something
}
P.S. If you want to filtering all array elements, you can use filter_var_array
<?php
$interests[50] = array('fav_beverages' => "beer");
?>
now i need the index (i.e. 50 or whatever the index may be) from the value beer.
I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.
please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.
thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer");
$interests[50] = array('fav_cuisine' => "arabic");
$interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.
This should work in your case.
$interests[50] = array('fav_beverages' => "beer");
function multi_array_search($needle, $interests){
foreach($interests as $interest){
if (array_search($needle, $interest)){
return array_search($interest, $interests);
break;
}
}
}
echo multi_array_search("beer", $interests);
If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:
$needle = 'beer';
foreach ($interests as $index => $arr) {
foreach ($arr as $value) {
if ($value == $needle) {
echo $index;
break;
}
}
}
Demo
can anybody let me know why array_search doesnt works for me? All i want is to search value and and get corresponding key value
for eg if i search wiliam i should get 4.. Its simple but aint working for me
<?php
$fqlResult[0]['uid']='1';
$fqlResult[0]['name']='Jay';
$fqlResult[1]['uid']='2';
$fqlResult[1]['name']='UserName2';
$fqlResult[2]['uid']='3';
$fqlResult[2]['name']='Frances';
$fqlResult[3]['uid']='4';
$fqlResult[3]['name']='William';
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname="'".$fqlResult[$i]['name']."'";
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
}
echo "<pre>";
print_r($userdb);
echo "</pre>";
echo array_search('4', $userdb);
?>
It doesn't work because array_seach searches values and "William" is a key. To complicate things, your values and keys are wrapped in single quotes during the for loop.
You'd want to do something like this:
if ( ! empty($userdb["'William'"]) )
{
// Echoes "'4'"
echo $userdb["'William'"];
}
// To find user ID "'4'"
// Outputs "'William'"
echo array_search("'4'", $userdb);
If you don't want things wrapped in single quotes, you'll need to change your for loop as follows:
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['name'];
$userdb[$userdbname]=$fqlResult[$i]['uid'];
}
if ( ! empty($userdb["William"]) )
{
// Outputs "4" (without the single quotes)
echo $userdb["William"];
}
// To find user ID "4" (without the single quotes)
// Outputs "William"
echo array_search('4', $userdb);
array_search() searches values, not keys.
If you want to check the existence of something that you use as a key in an array, you can just use isset:
if(isset($userdb['William'])) {
echo "$userdb[William] is William's uid!";
}
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['uid'];
$userdb[$userdbname]=$fqlResult[$i]['name'];
}
Change
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
with this
$userdb[$i] = "{$fqlResult[$i]['name']}";
array_search only works with arrays of scalar data. You're trying to search an array of arrays. You can easily search the array yourself:
function search_array_col($array, $col, $val)
{
foreach ($array as $key => $a)
{
if ($a[$col] == $val) return $key;
}
return null;
}
echo search_array_col($fqlResult, 'name', 'William') , "\n";
echo search_array_col($fqlResult, 'uid', '4') , "\n";
Edit: n/m, I misread your code. However, you could still use this to search your original array, so I'll leave the answer for reference.
try this:
foreach($fqlResult as $result)
{
$name = $result["name"];
$uid = $result["uid"];
$userdb[$name] = $uid;
}
then you want to use array_key_exists() to find the key. array_search() only works for searching values, not keys.
$nameExists = array_key_exists("William",$userdb);
You can remove the quotes in the $userdbname="'".$fqlResult[$i]['name']."'";
rewrite it to
$userdbname= $fqlResult[$i]['name'];