I’m working on a project today and building a credit card checkout form for what seems like the 1,000th time. It occurred to me that a US State Helper would save me from having to 1) look up all of the states every time, and 2) dump them into an array and build out functions for easy conversions and validation. I figure this may help some people out there, so enjoy!
If you are using the Spark, install as usual. Otherwise, the helper file (helpers/state_helper.php) will need to be moved into your ‘application/helpers’ project directory.
No configuration involved. Just load the helper as your would any other helper.
<?php // Spark $this->load->spark('state-helper/1.0.0'); // Or, Helper file $this->load->helper('state');
There are currently four helper functions available to simplify dealing with US states in CodeIgniter.
- state_array() — Returns an array of US state names where the array’s keys are the corresponding two-letter abbreviation.
- state_dropdown($name [, $selected [, $id [, $class]]]) — Returns the HTML for a <select> dropdown where the <option> values are the states’ two-letter abbreviations and the displayed values are the full state names.
- $name — The name to be placed on the <select> element.
- $selected (optional) — The particular state’s two-letter abbreviation to be set as the default.
- $id (optional) — ID attribute to be placed in the <select> tag.
- $class (optional) — Class attribute to be placed in the <select> tag.
- abbr_to_name() — Converts state’s two-letter abbreviations into their full state name.
- name_to_abbr() — Converts full state names into their respective two-letter abbreviations.
- is_valid_state() — Checking function to see that the provided full state name OR two-letter abbreviation is valid. Returns boolean TRUE or FALSE.