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.
Related
I just started learning PHP and I am having some difficulties with some of the coding.
Hopefully, someone could help me a little.
I'm using this:
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1) {
echo " $a1";}}
The echo will write several results of $a1 depending on how many were selected in the form.
What I want is to save those results to some values so I can add them in MySQL.
Something like this:
if(!empty($_POST['yyy']))
{
foreach($_POST['yyy'] as $a1)
{
echo " $a1"; where $a1 will create a $result1,$result2,$result3(for each isset)
}
}
Then if I use:
echo "$result2";
it will give me the second result.
Not clear whether you are asking about this kind of result or not. But you can use an array to store each values inside the foreach loop.
var data=[];// define an array to access outside of if statement later..
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1){
data[]=$a1;
//or can use array_push() method
array_push(data,$a1);
}
}
/*this will give the second result(because array indexing starts from 0. So to get third result
use data[2])*/
echo data[1];
Furthermore by echoing quoted variable will not give the value of that variable but gives a string literal.
echo "$result2" //output---> $result
I have a feeling I'm going to get scolded for this but here is the question.
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs['bullet_($seqnumber)'];?>
} // this one doesn't work.
I've tried
with curly brackets {}
I basically have a few columns that are named same except for number at the end (bullet_1, bullet_2, bullet_3, etc.) and want to get the results using a loop.
Your problem is, that PHP doesn't replace variables inside strings enclosed with single quotes. You need to use $db_rs["bullet_{$seq_number}"] or one of those:
<?php
foreach ($seq_numbers as $seq_number) {
$key = 'bullet_' . $seq_number;
echo $db_rs[$key];
}
Even shorter, but a little less clear:
<?php
foreach ($seq_numbers as $seq_number) {
echo $db_rs['bullet_' . $seq_number];
}
An entirely different approach would be to loop over the result array. Then you don't even need $seq_numbers. Just as an afterthought.
<?php
foreach ($db_rs as $key => $value) {
if (substr($key, 0, 7) == 'bullet_') {
echo $value;
}
}
Oh...and watch out for how you spell your variables. You are using $seq_number and $seqnumber.
<?php echo $db_rs['bullet_'.$seqnumber];?>
why not:
$db_rs['bullet_'.$seqnumber]
If not, what are your fields, and what does a var_dump of $db_rs look like?
try this...
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs["bullet_($seqnumber)"];?>
} // now it works.
I have nested arrays and want to append the content of one array into another when the keys match. Here is my function but instead of appending it is replacing.
function MergeArrays($arr, $ins)
{
if(is_array($arr))
{
if(is_array($ins))
foreach($ins as $k=>$v)
{
if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
{
$arr[$k] = MergeArrays($arr[$k], $v);
}
else
{
// This is the new loop :)
// while (isset($arr[$k]))
// $k++;
// HERE IS WHERE I WANT TO APPEND INSTEAD OF ADD
$arr[$k] = $v;
}
}
}
else if(!is_array($arr)&&(strlen($arr)==0||$arr==0))
{
$arr=$ins;
}
return($arr);
}
Any recommendations?
Thanks
You can merge the entries by either adding the arrays together, or using array_merge to merge the arrays into a new one.
Any reason you're not using array_merge_recursive to solve this without custom code?
I'm not sure I'm reading the question properly, I'm a little confused as to what you're doing, but this might help:
As far as I can tell, you want to append to the value of $arr[k] with the value of $v. Therefore you want to concat these things together.
Therefore you want to use .= instead of = on the line below your comment.
I am using PHP 5.3.6
I have the following code below. Everything works fine except for the last line which attempts to to return a value based on the position in the array as opposed to the associative name. Can anyone explain why this takes place and how I can build the array so that I can reference an item either by the associative name or position number?
Thanks.
<?php
class myObject {
var $Property;
function myObject($property) {
$this->Property = $property;
}
}
$ListOfObjects['form_a'] = new myObject(1);
$ListOfObjects['form_b'] = new myObject(2);
$ListOfObjects['form_c'] = new myObject(3);
$ListOfObjects['form_d'] = new myObject(4);
echo "<pre>";
print_r($ListOfObjects);
echo "</pre>";
echo "<hr />";
foreach ($ListOfObjects as $key => $val) {
echo "<li>" . $ListOfObjects[$key]->Property . "</li>";
}
echo "<hr />";
echo "<li>" . $ListOfObjects['form_a']->Property . "</li>"; // Works ok.
//Edit: ------------------------------------------------------------
//Edit: Everything above is for context only
//Edit: I'm only interested in the line below and why it does not work
//Edit: ------------------------------------------------------------
echo "<li>" . $ListOfObjects[0]->Property . "</li>"; //Does not work.
?>
function value_from_index($a,$k){
return array_slice($a,$k,1);
}
If you just want the first/last element of an array, try end($array) for the last item without destroying it and reset($array) to get the first.
Don't use reset and end if you're looping through an array as Flambino notes, this indeed results in some unexpected behaviour.
For anything inbetween you'll need to use array_slice()
Not the nicest way of doing it, but effektive and readable:
$i = 0;
$last = count($ListOfObjects);
foreach($ListOfObjects as $obj) {
if($i == 0) {
//do something with first object
$obj->property;
else if ($i == ($last-1)) {
//do something with last object
$obj->property;
}
}
PHP arrays aren't like arrays you know from most other programming languages, they are more like ordered hash tables / ordered dictionaries - they allow for access by named index and retain order when new items are added. If you want to allow access with numeric indices to such an array you have to define it that way or use one of roundabout ways given in other answers.
In your case you can use a single line of code to allow access by index:
$ListOfObjects += array_values($ListOfObjects);
This will extend your array with the same one but with numeric indices. As objects are always passed by reference, you can access the same object by writing $ListOfObjects['form_b'] and $ListOfObjects[1].
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'];