Solved

Inserting an element into an associative array

Posted on 2014-02-14
6
371 Views
Last Modified: 2014-02-16
I can produce an associative array in PHP.

I would like to use the array for a dropdown field in a page.

I would like to insert a "Select an Option" as the first element of the array.

Thank you in anticipation of your help.

John
0
Comment
Question by:johnecollins
6 Comments
 
LVL 28

Assisted Solution

by:becraig
becraig earned 125 total points
ID: 39860757
Not sure how you are populating but something like this should work:
<select name="element">
<option value="0">Please Select an Option</option>
<?php
    try
    {
        /*** query the database ***/
        $result = DB::getInstance()->query("SELECT atomicnumber, english FROM elements");

        /*** loop over the results ***/
        foreach($result as $row)
        {
            /*** create the options ***/
            echo '<option value="'.$row['atomicnumber'].'"';
            if($row['atomicnumber']==42)
            {
                echo ' selected';
            }
            echo '>'. $row['english'] . '</option>'."\n";
        }
    }
    catch(PDOException $e)
    {
        echo 'No Results';
    }
?>
</select>
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 125 total points
ID: 39861190
One does not usually "insert a first element" in an associative array.  The nature of associative arrays is such that the names of the keys are the important information, not the position of the values (as is the case in a numerically indexed array).  And if you want an HTML select list, you would need it to be a string variable anyway.  So the right place to add the "select" tag and the default option is in the creation of the HTML.  This script shows how you might do that.  (Please install it, run it and use "view source" to see the effect).

<?php // RAY_temp_johnecollins.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28365493.html

// AN ASSOCIATIVE ARRAY
$arr = array
( 'a' => 'aaa'
, 'b' => 'bbb'
, 'c' => 'ccc'
)
;

// START TO CREATE A SELECT LIST FROM THE ARRAY
$sel = '<select name="thing">' . PHP_EOL;

// ADD A NULL SELECTION
$sel .= '<option value="" selected>Select an Option</option>' . PHP_EOL;

// ADD THE OPTIONS (KEY / VALUE PAIRS)
foreach ($arr as $key => $val)
{
    $sel .= '<option value="' . $key . '">' . $val . '</option>' . PHP_EOL;
}

// WRAP UP THE HTML TAG
$sel .= '</select>' . PHP_EOL;

// WRITE THE TAG TO THE BROWSER OUTPUT STREAM
echo $sel;

Open in new window

Here is the alternative version, using a single array, made from two associative arrays.  You can depend on the order of the data from array_merge(), but be aware that matching keys will overwrite the values.

<?php // RAY_temp_johnecollins.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28365493.html

// AN ASSOCIATIVE ARRAY
$arr = array
( 'a' => 'aaa'
, 'b' => 'bbb'
, 'c' => 'ccc'
)
;

// CREATE A NEW ARRAY WITH THE DEFAULT SELECTION
$new = array("" => 'Select an Option');

// MERGE IN THE 'REAL' OPTIONS
$new = array_merge($new, $arr);

// START TO CREATE A SELECT LIST FROM THE ARRAY
$sel = '<select name="thing">' . PHP_EOL;

// ADD THE OPTIONS (KEY / VALUE PAIRS)
foreach ($new as $key => $val)
{
    $sel .= '<option value="' . $key . '">' . $val . '</option>' . PHP_EOL;
}

// WRAP UP THE HTML TAG
$sel .= '</select>' . PHP_EOL;

// WRITE THE TAG TO THE BROWSER OUTPUT STREAM
echo $sel;

Open in new window

0
 

Author Comment

by:johnecollins
ID: 39861211
becraig

Thank you for your response.

I am working with Codeigniter Framework and manage my application into model, view and controller architecture.

So the controller calls a function in the model to select data and I pass the array to a view and it is displayed by a view.

I would like to insert at the start of the array "Select a value" this will allow me the opportunity to test whether the field has been set - it no longer equals "Select a value" but a value from the array.

So thank you for the answer you have previously sent me but unfortunately it isn't what I want and I apologise for not making myself clear.

Thanks John
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 125 total points
ID: 39861343
There's a couple of ways of doing this depending on your setup. You could do it all in the model. Create the array with your 'Select an Option' and then just add the database records to that array:

$myArray = array('Select An Option');
foreach ($dbrecord as $option):
    $myArray[] = $option;
endforeach;

Open in new window

Another way is to add the value to the array once you've got the data back into your controller. array_unshift() maybe

A third way is to just manually add the Select an Option in the view:

<select>
<option>Select an Option</option>
<?php
foreach ($options as $option):
    printf("<option>%s</option>",$option);
endforeach;
?>
</select>

Open in new window

Which method you choose will depend largely on the data your model returns. Show us your model (or at least the data returned) and we can be more specific
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 125 total points
ID: 39861721
greetings  johnecollins, , many in PHP do not realize that the "Math" operator "+" works on arrays to ADD arrays together, if you want to push an array element on top of it's element stack you might try -

$array1 = array("one" => "first", "two" => "second", "three" => "third");
$array1 = array("Select an Option" => "Select an Option") + $array1;
     // the +  ADDS array to beginning

there are several ways to do this, and as a PHP developer, it is very necessary to know alot of these array function listed here in the manual -
    http://us1.php.net/manual/en/ref.array.php
you will do better code work if you know more of these functions.

you can also do -
$array1 = array("one" => "first", "two" => "second", "three" => "third");
$array1 = array_reverse($array1);
$array1["Select an Option"] = "Select an Option";
$array1 = array_reverse($array1);// "Select an Option" is now on TOP position
0
 

Author Closing Comment

by:johnecollins
ID: 39862988
Hi All,
Thank you very much for helping to answer this question and affording me the opportunity to select which methods I will use for my future developments.

I have awarded equal points  to each of you thank you very much

John
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now