0

I have an array called $brand_terms. I'm accessing two objects in this array. In this case 'name' and 'slug'. I'm then trying to set values of these objects in an associative array called $values. The code is below:

$brand_terms = get_terms("pa_brand");
$values = array(
    foreach ($brand_terms as $brand_term){
        $brand_term->name => $brand_$term->slug, 
    }
);

The problem I have is with the separator ,. So the comma at the end of $brand_term->name => $brand_$term->slug,. If the loop is at the last value in the array, the comma is not needed and the the code is broken. Is there a nice way to remove this comma from the last iteration of the foreach loop?

Thanks

2 Answers 2

7

That syntax is completely wrong. You cannot have a loop within an array declaration.

Instead create the array, then push elements into it during the loop:

$brand_terms = get_terms("pa_brand");
$values = array();
foreach ($brand_terms as $brand_term){
    $values[$brand_term->name] = $brand_$term->slug; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, PHP doesn't really have any problem with an extra comma in the last element of an array.
2

Actually, the problem isn't at all with the , literal, in fact that isn't valid PHP. You can't have a foreach loop inside of an array declaration.

The best approach is to define the array and then loop through the get_terms() return value as follows:

$values = array();

foreach( get_terms('pa_brand') as $term )
{
    $values[$term->name] = $term->slug;
}

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.