I use foreach to loop the array below and then making the order number to be store in the database,
$items_variable = array(
'page_id',
'page_content_1',
'page_content_2',
'page_content_3',
'page_content_4',
...
);
The code only loop 4 items from the array above (but what if I have these page_content_# increased in the future?)
foreach( $items_variable as $item_variable )
{
if (in_array($item_variable, array(
'page_content_1',
'page_content_2',
'page_content_3',
'page_content_4'
)))
{
if($item_variable == 'page_content_1') $order_in_page = 1;
if($item_variable == 'page_content_2') $order_in_page = 2;
if($item_variable == 'page_content_3') $order_in_page = 3;
if($item_variable == 'page_content_4') $order_in_page = 4;
....
}
}
The current method I have above doesn’t look good to me especially when it comes to the line like this,
if($item_variable == 'page_content_1') $order_in_page = 1;
I will add more lines like this when I have page_content_# increased in the future and the script will look pretty ugly I suppose.
What if I have another type of data with order number (for instance – code_1, code_2, etc)? Then I have copy the code above and change the item name each time – this looks pretty gloomy isn’t!
How can I make it better and dynamic?
Associative array
You can do this:
Dynamically extracting last part of string
Or do it completely dynamically assuming that it’s always
page_content_{$order_in_page}, either with regexp as hackartist suggested or use “oldschool method”:I recommend studying examples from
intval()documentation 🙂SwitchstatementPhp provides switch which allows you to handle many different cases with relatively small amount of code.
I’d however do this only if first two options wouldn’t work out for you (eg. you need to call different function for each case).