Jump to content

Assigning variables to themselves using curly braces


marcbraulio

Recommended Posts

I didn't know how to describe this, so please excuse my title.

 

As most of you know, this is possible:

foreach($items as $key => $item)
{
${$key} = $item;
}

// I would then be able to access it like so:
$key // or whatever the value of "$key" is.

 

However, how could I append something extra to the ${$key} variable?

 

Instance:

foreach($items as $key => $item)
{
$my_{$key} = $item;
        // or 
        ${$key}_arr = $item;
}

// So that the end result of my variable becomes like so:
$my_key 
// or
$key_arr
// Instead of just
$key // or whatever the value of "$key" is.

 

Is there a known method for this?

 

Any input is appreciated, thank you.

Link to comment
Share on other sites

You are much better off avoiding variable variables all together (they are slow and use a lot of memory). You could easily achieve the same results using arrays in this instance.

 

Thank you for the insight, I'll be definitely following the advice.

Will using array assignments like so:

 

foreach($items as $item)
{
$my_array[$item] = $item;
}

also affect performance? I am just trying to avoid using things like "my_array[0]" for readability purposes.

Link to comment
Share on other sites

How would using numeric keys affect readability? Also, what happens if you have multiple identical values in $items? Your resulting array would only have a single copy of that value. This might not be desired.

 

Here's an example of what I mean

<?php

// This forces a browser to output as plain text, rather than HTML.
header( 'Content-Type: text/plain' );

$items = array( 'foo','bar','baz','foobar','bar','baz','bar' );
echo "Source Array:\n";
print_r( $items );

$new_array = array();
foreach( $items as $item ) {
$new_array[$item] = $item;
}
echo "Generated Array:\n";
print_r( $new_array );

?>

 

Output:

Source Array:
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
    [3] => foobar
    [4] => bar
    [5] => baz
    [6] => bar
)
Generated Array:
Array
(
    [foo] => foo
    [bar] => bar
    [baz] => baz
    [foobar] => foobar
)

 

What exactly are you trying to accomplish?

Link to comment
Share on other sites

What exactly are you trying to accomplish?

 

I asked the question above for my general use, but here is a specific example where I would use the assignment of array keys inside a foreach loop, where readability is essential.

 

This is a modular CMS i am building for my personal use.

 

/*	
*	get the itemid of the page else assign it '1' which is the id of the front page. 
*	every page will have an unique item id.
*	example of url www.example.com/index.php?comp=components&itemid=22  
*/
if (isset($_GET['itemid'])) 
{ 
$itemid = $_GET['itemid'];
}
else
{
$itemid = 1;
}

/*	
*	select from columns where the modules status is 1 (enabled)
*	and the page itemid is equivalent to the page's itemid.
*/
$sql = "SELECT mod_name, mod_position, mod_item_id 
	FROM module
	WHERE mod_status = 1 AND mod_item_id = $itemid"; 

$stmt = $db->query($sql);

// fetch results into the modules class for itemid manipulation.
$objs = $stmt->fetchALL(PDO::FETCH_CLASS, 'modules');

// break down the results and assign them to a name convention
foreach($objs as $obj)
{
// example: $module_array[nav] = nav
$module_array[$obj->mod_position] = $obj->mod_position;

// example: $name = nav_module
$name = $obj->mod_position . '_module';

// example: $module_array[nav_module] = menu
$module_array[$name] = $obj->mod_name;
} 

/* 
*	this specific module position is called nav.
*	if this position is set the $module_array[nav_module] will call the appropiate module
*	in this case the $module_array['nav_module'] = menu
*/
if (isset($module_array['nav'])) //&& in_array($itemid, $module_array['nav_itemid']) ) 
{
echo load_module($module_array['nav_module']);
}

 

By the way, if you have a better way of accomplishing this "modular system" please don't hesitate to give me your input.

Link to comment
Share on other sites

That's a very small scope of your CMS system, so it's difficult to critique the system as a whole.

 

I'm assuming `mod_position` is unique? I'm not sure the point of storing mod_position and mod_name under two different keys. You could simply use.

<?php
foreach($objs as $obj) {
$module_array[$obj->mod_position] = array( 'item_id'=>$obj->mod_item_id, 'name'=>$obj->mod_name );
}

if( isset($module_array['nav']) ) {
echo load_module( $module_array['nav']['name'] );
}
?>

 

Or, if you didn't need the ID (in which case you shouldn't be SELECTing it in your query), you can use

 

<?php
foreach($objs as $obj) {
$module_array[$obj->mod_position] = $obj->mod_name;
}

if( isset($module_array['nav']) ) {
echo load_module( $module_array['nav'] );
}
?>

 

Hope that helps.

Link to comment
Share on other sites

That's a very small scope of your CMS system, so it's difficult to critique the system as a whole.

 

I'm assuming `mod_position` is unique? I'm not sure the point of storing mod_position and mod_name under two different keys. You could simply use.

<?php
foreach($objs as $obj) {
$module_array[$obj->mod_position] = array( 'item_id'=>$obj->mod_item_id, 'name'=>$obj->mod_name );
}

if( isset($module_array['nav']) ) {
echo load_module( $module_array['nav']['name'] );
}
?>

 

This is a much more convenient way to do it, thank you! I simply didn't think of doing it that way and you are right, I don't have a need to store mod_position and mod_name under two different keys.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.