PHP array_search not working - php

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'];

Related

How do i use variable in array index?

I've got a number of individual items. Currently, I go through them individually but i would like to loop through them. If these were number indexes, I would have no problem there. But since these are names- it's more of a challenge. Couldn't find anything, but i may be looking for a wrong thing (are these really array indexes)?
Currently, I check and output them in the following way.
if ($term_meta['term_1']) { echo '"'.$term_meta['term_1'].'",'; }
if ($term_meta['term_2']) { echo '"'.$term_meta['term_2'].'",'; }
if ($term_meta['term_3']) { echo '"'.$term_meta['term_3'].'",'; }
if ($term_meta['term_4']) { echo '"'.$term_meta['term_4'].'",'; }
if ($term_meta['term_5']) { echo '"'.$term_meta['term_5'].'",'; }
if ($term_meta['term_6']) { echo '"'.$term_meta['term_6'].'",'; }
if ($term_meta['term_7']) { echo '"'.$term_meta['term_7'].'",'; }
if ($term_meta['term_8']) { echo '"'.$term_meta['term_8'].'",'; }
And I would like to achieve similar result with loop looking somewhat like this. But I can't make these variables work.
for ($terms_num = 1; $terms_num<=8; $terms_num++) {
if ($term_meta['term_'+$terms_num]) { echo '"'.$term_meta['term_'+$terms_num].'",';}
}
in php you concatenate with '.'
also you cant check if the key is in the array like this instead use array_key_exists (or something similar I dont claim to know all the php libs)
for ($terms_num = 1; $terms_num<=8; $terms_num++) {
if (array_key_exists('term_'.$terms_num,$term_meta) {
echo '"'.$term_meta['term_'.$terms_num].'",';
}
}
It's much easier to use array_filter and implode.
Array_filter will remove any null or empty values, and implode will build a string from your array.
echo '"' . implode('","', array_filter($term_meta)) . '"';
See example here:
https://3v4l.org/vCrMM
Looping as the other answer will create a trailing comma that is (probably) unwanted.
Using implode will not create any trailing commas.

how to get the index of an array using the value in php

<?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

I have a problems. I need to split string variable in php

I have code which extracting keywords, this keywords with td/idf rating and other options are in $tags. Variable k-keyword consisting of this word. but if i want to print all of these keywords, this keywords look like: one long string, I need to have this keywords separated with " ", or ","...
I have something like that in php
foreach($tags->keywords as $k) {
//$metTag = parseTags($k->keyword);
print_r ($k->keyword);
}
and output is
userarmethodrecommenddelivthidecisconsidactionruleadaptinformmodelcontentsituatbasiengagon-demandproactivmood
but I need output like that:
Array (
[user]
[ar]
[method]
[recommend]
...
)
You can just do
print_r($tags->keywords);
Or this way :
$array = array();
foreach($tags->keywords as $k) {
$array[] = $k->keyword;
}
print_r($array);
Try this:
echo '<pre>';
foreach($tags->keywords as $k) {
print_r ($k->keyword);
}
echo '</pre>';
From the code that you've provided, it looks like $k is an object with the field keyword. Since $tags->keywords is an array you could try to just use print_r($tags->keywords); instead of the loop but this will display all of the fields in the array $tags->keywords as well as dump all of the fields in the $keywords objects within the array. You might also try print_r($k) but again, this will also print all of the fields in the $k object.
Another option would be to simply do this:
print "Array (\n";
foreach($tags->keywords as $k) {
//$metTag = parseTags($k->keyword);
print $k->keyword . "\n";
}
print ")\n"

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.

Can I specify which key I want in a foreach loop?

If I have an array called $animalarray with keys dog, cat, bird, can I specify which key I want to use in a foreach loop?
I'm doing something like this right now but it just returns all the values from the array
foreach($animalarray as $species=>$bird)
{
echo $bird;
}
I'd like this to only echo out the value under the key Bird, but this returns all values under all the keys.
Why don't you just do echo $animalarray['bird'];?
You could also do this, but it's unnecessary:
foreach($animalarray as $species=>$bird) {
if ($species == 'bird') {
echo $bird;
}
}
Do it like this:
$allowedKeys = array('dog');
foreach($animalarray as $species=>$bird)
{
if(array_key_exists($species, $allowedKeys)) {
echo $bird;
}
}
It will output matches only for dogs.
If animal array is from database, then select it with aditional condition.
Or you can use simple IF statement http://www.php.net/manual/en/control-structures.if.php

Categories