0

I have a list of variables i need to create like so:

$meta_2_length = get_post_meta( get_the_ID(), 'meta-2-length', true );
$meta_2_loft = get_post_meta( get_the_ID(), 'meta-2-loft', true );
$meta_2_lie = get_post_meta( get_the_ID(), 'meta-2-lie', true );
$meta_2_bounce = get_post_meta( get_the_ID(), 'meta-2-bounce', true );

I need to make these for the numbers 2 - 14 so I figured the best way would be a loop. I am new to php but want to write as clean as possible. I thought this might work:

for($i = 0; $i <= 14; $i++) {
   ${"meta_$i_length"} = "get_post_meta( get_the_ID(), 'meta-$i-length', true );";
}

but when it doesnt seem to be working when I echo $meta_3_length

1
  • Numeric variables like this are almost always wrong. This is what arrays are for. Commented Oct 14, 2015 at 18:45

4 Answers 4

1

My recommendation for you is create an array. And give the array values in the loop.

example

$foo = array();    
for($i = 0; $i <= 14; $i++) {
   $foo[] = "get_post_meta( get_the_ID(), 'meta-$i-length', true );";
}

then echo data by using the array

Sign up to request clarification or add additional context in comments.

2 Comments

Why did you put the call to get_post_meta in quotes?
If I use this (without qoutes around get_post_meta) and I echo it out like <?php if( !empty( $meta_length[3] ) ) { echo $meta_length[3]; } ?> I get nothing.
0

Use an array of associativer arrays.

$metas = array();
$id = get_the_ID();
for ($i = 0; $i <= 14; $i++) {
    $metas[] = array(
        'length' => get_post_meta($id, "meta-$i-length", true),
        'loft' => get_post_meta($id, "meta-$i-loft", true),
        'lie' => get_post_meta($id, "meta-$i-lie", true),
        'bounce' => get_post_meta($id, "meta-$i-bounce", true)
    );
}

Now you can do echo $metas[3]['length'];.

1 Comment

Worked perfect and clean. Also gives me a better understanding of how to set up PHP variables like i would in JS
0

You can use variable variables:

for($i = 0; $i <= 14; $i++) {
   $varname = "meta_$i_length";
   $$varname = get_post_meta( get_the_ID(), 'meta-$i-length', true );
}

Comments

0

You can use extract with an associative array:

$arr = [];
for($i = 0; $i <= 14; $i++) {
    $arr["meta_{$i}__length"] = get_post_meta( get_the_ID(), "meta-{$i}-length", true);
}
extract($arr);

Then, you can do echo $meta_3__length and get the result of the function call get_post_meta( get_the_ID(), "meta-3-length', true);

I hope it helps

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.