WordPress & PHP: Variable variables (dynamic variables from strings)
<?php
$acf_review_app_fields = array(
"color-primary",
"color-header-bg",
"color-footer-bg",
"color-site-bg",
"color-layout-bg",
"rp_nap_business_name",
"rp_nap_phone",
"rp_website_url",
);
// Iterate through field names defined in $acf_review_app_fields array
// Create PHP variables named the same with dashes converted to underscores
// for easy access later
foreach ( $acf_review_app_fields as $acf_field){
// Populate variable value with data from ACF field
$var = get_field( $acf_field, "option" );
// Rename array entry with dashes swapped for underscores so they work as variables
$acf_field = str_replace("-", "_", $acf_field);
// Create a variable from the string with the value set to the ACF data
${$acf_field} = $var;
}
// Access like so:
echo $color_primary;
echo $color_header_bg;