How to write an ARRAY in a FOREACH loop with PHP for WordPress

I am new to arrays, and need a little help.

Basically what I want to do is to register menus on the go. So I made a loop that I thought would take care of that. Now the problem is that I don’t really know how to register arrays properly.

Read More
$lim = array(); 

foreach ( $new_menus as $menu => $value ) {

    $rname = get_post_meta(1,"$menu",true);                 
    $slugpath = preg_replace('/[^a-zA-Z0-9]/', '_', $rname );

    $lim[] = $slugpath => __( $rname );

    }
}

In the case above $slugpath would be header-menu and $rname would be Header Menu. Ultimately I want an array like the one below. How do I do this?

array(
  'header-menu' => __( 'Header Menu' ),
  'footer-menu' => __( 'Footer Menu' ),
  'left-menu' => __( 'Left Menu' )
);

Related posts

Leave a Reply

1 comment

  1. you should assign it to array like this:

    $lim[$slugpath] = __($rname);
    

    Additionally:

    Unless your $new_menus array have it’s values in keys, you should use $value var in get_post_meta function instead of key $menu, so it would look like this:

    $rname = get_post_meta(1,$value,true); 
    

    And if you want - symbol in slugged text, you should replace _ symbol in your preg_replace with it, and use strtolower() on it if you want it all lowercased:

    $slugpath = preg_replace('/[^a-zA-Z0-9]/', '-', $rname );
    $slugpath = strtolower($slugpath);