Solved

Inserting an element into an associative array

Posted on 2014-02-14
6
375 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 29

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 109

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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 43

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 34

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

860 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