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)

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


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

for ( $i = 1; $i &lt; 14; $i++) {
$group_bio = 'group_' . $i . '_bio';
$$group_bio = get_post_meta($object-&gt;ID, '_group_' . $i . '_bio', true);
echo '
<h3>Group '.$i.'</h3>
<div>

<label for="'.$group_bio.'">GROUP Bio</label>
'.wp_editor( $$group_bio, $group_bio, array(false, true, $group_bio, 4) ).'

</div>
';
}

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:

for($i=1; $i < 14; $i++) {
$new_meta_value = ( isset( $_POST['group_' . $i . '_bio'] ) ? $_POST['group_' . $i . '_bio'] : '' );
$meta_value = get_post_meta( $post_id, '_group_' . $i . '_bio', true );
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, '_group_' . $i . '_bio', $new_meta_value, true );
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, '_group_' . $i . '_bio', $new_meta_value );
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, '_group_' . $i . '_bio', $meta_value );
}

Related Posts