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
Related
We have two array variables with names first_names and last_names that have an uncertain number of members. We intend to select an appropriate loop and only use the same information loop with the corresponding first and second variable information respectively.
You must use a loop.
<؟php
$first_names=array('jack','root','admin');
$last_names=array('jack111','root222','admin333'');
foreach (array_combine($first_names ,$last_names) as $fname => $lname)
{
print_r($fname.$lname."<br>");
};
?>
Try this. Simple n easy to understand
$first =count($first_names);
$last =count($last_names);
for($i=1;i<=$first;$i++)
{
echo $i;
}
for($i=1;i<=$last;$i++)
{
echo $i;
}
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"
for example say i have an object array called $list looks like this:
<(stdClass)#16 (3) {
["1"]=>
<(8) "50504496"
["2"]=>
<(8) "12435374"
["3"]=>
<(8) "12436374"
Im doing a foreach on the object array and removing them if they exist in the database i.e
foreach($list as $l){
//do the query
if( it exists){
//remove from objects: this is where i need help!!
}
}
i have the db logic, im just stuck to know how i can remove objects, i was thinking maybe i should create a new object and add them thier. thanks
}
Use: unset
foreach($list as $key => $obj){
if( exists .. ) {
unset($list[$key]);
}
}
run your query and if it returns >0 number of rows then you have a result, use unset($object->$var) to unset a variable
Try like:
foreach($list as $li)
{
if($li)
{
//copy into another array.
}
}
i thnk its may simple
Try like:
$i=0;
foreach($list as $li)
{
if($li)
{
$b[i] = $li;
$i++;
}
}
array '$b' will hold the values in $list which are not null
My problem is:
I have an array called $ownerArray that another array need to check against and if a key exists in both arrays display the value of the matching key. $ownerArray is populated by a database so i can't just write an ir statement within a if statement.
$ownerArray will look like this:
$ownerArray = array(0 =>'Name0',1 =>'Name1',2 =>'Name2',3 =>'Name3');
Then I have another array called $Users that has a various number of values depending on what the user selects, so $Users could look like this:
$Users = '1,2'
or Like this:
$Users = '1,3'
$Users is never the same.
But I need the $value of $ownerArray to display if any of the values integers of $Users match any $key of $ownerArray
Example:
foreach($ownerArray as $key => $value)
{
if(in_array($key,array($Users)))
{
print $value;
}
}
This method stops at the fist match and displays the correct name. The loop doesn't continue printing if more values match.
What im looking for is if $Users = '1,3' my for loop will print Name1 and Name3 from the $ownerArray.
Thanks for the help!
ps i know i could use if($key==1 || $key ==2) but that will not work for this case.
$merged = array_flip(array_intersect(array_flip($owners), explode(',', $users)));
something like this could work
<?php
$ownerArray = array(0 =>'Name0',1 =>'Name1',2 =>'Name2',3 =>'Name3');
$users = explode(',','1,2');
if(count($users) > 0){
foreach($users as $user){
if($key = array_search($user,$ownerArray)){
echo $key;
}
}
}
?>
Just invert your logic. You are actually wanting to cycle through your users, and print something if they exist in the owner array, not the other way around. (Apologies if this code is slightly off, but you get this idea.)
foreach($Users as $value)
{
if(in_array($value,array($ownerArray)))
{
print $ownerArray[$value];
}
}
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'];