0

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].'",';}
}
3
  • you use . to concatenate, + will try to add the two values mathematically Commented Apr 1, 2019 at 19:49
  • like this? $term_meta['term_'.$terms_num] Commented Apr 1, 2019 at 19:53
  • php.net/manual/en/control-structures.foreach.php Commented Apr 1, 2019 at 20:00

2 Answers 2

1

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].'",';
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

which to be honest you actually used in the echo line oO
simple enough. Thank you!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.