Samij
Samij

Reputation: 81

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].'",';}
}

Upvotes: 0

Views: 658

Answers (2)

Andreas
Andreas

Reputation: 23958

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.

Upvotes: 0

jonathan Heindl
jonathan Heindl

Reputation: 851

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].'",';
    }
}

Upvotes: 1

Related Questions