Dynamic Variables in PHP

say you have 10 group names, labeled ‘$group_1’, ‘$group_2’, etc. and you want to display each of them. a quick way to do that is to use dynamic variables (aka variable variables)

1for ($i = 1; $i < 11; $i++) {
2echo ${'group_' . $i};
3}


that’s a super simple implementation. i needed to use it for a recent project — it was pretty intense to figure out the logic, but this is what i came up with

i needed to add some custom post meta fields to the wordpress admin for 13 groups (simplified, adding a WIZZY editor for the editor to add bios for each group), but didn’t want to write 13 versions of pretty much the same code, save for a incrementing variable in the name

01for ( $i = 1; $i &lt; 14; $i++) {
02$group_bio = 'group_' . $i . '_bio';
03$$group_bio = get_post_meta($object-&gt;ID, '_group_' . $i . '_bio', true);
04echo '
05<h3>Group '.$i.'</h3>
06<div>
07 
08<label for="'.$group_bio.'">GROUP Bio</label>
09'.wp_editor( $$group_bio, $group_bio, array(false, true, $group_bio, 4) ).'
10 
11</div>
12';
13}

one of the toughest parts to wrap my head around in the beginning was the $$group_bio variable. take it one line at a time:

$group_bio = 'group_' . $i . '_bio';

for example, the first iteration, that $group_bio variable will be ‘group_1_bio
the next line will then make ‘group_1_bio‘ into a variable: $group_1_bio, which will store the post_meta data stored in _group_1_bio

that snippet of code will make 13 of my WIZZY editors on the page — this keeps my functions.php leaner!

want to save the data and still keep your functions.php file clean?

this goes somewhere in your save_post class:

01for($i=1; $i < 14; $i++) {
02$new_meta_value = ( isset( $_POST['group_' . $i . '_bio'] ) ? $_POST['group_' . $i . '_bio'] : '' );
03$meta_value = get_post_meta( $post_id, '_group_' . $i . '_bio', true );
04if ( $new_meta_value && '' == $meta_value )
05add_post_meta( $post_id, '_group_' . $i . '_bio', $new_meta_value, true );
06elseif ( $new_meta_value && $new_meta_value != $meta_value )
07update_post_meta( $post_id, '_group_' . $i . '_bio', $new_meta_value );
08elseif ( '' == $new_meta_value && $meta_value )
09delete_post_meta( $post_id, '_group_' . $i . '_bio', $meta_value );
10}

Related Posts