Get list value in php

PHP Select Option

Summary: in this tutorial, you will learn how to use the element to create a drop-down list and a list box and how to get the selected values from the element in PHP.

A quick introduction to the element

The is an HTML element that provides a list of options. The following shows how to define a element in HTML:

label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)

The element has two important attributes:

  • id – the id associates the element with a element
  • name – the name attribute associates with the value for a form submission.

The element nested inside the element defines an option in the menu. Each option has a value attribute. The value attribute stores data submitted to the server when it is selected.

If an option doesn’t have the value attribute, the value attribute defaults to the text inside the element.

To select an option when the page loads for the first time, you can add the selected attribute to the element.

The following example selects the Green option when the page first loads:

label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)

Getting the selected value from a element

We’ll create a form that uses a element.

Читайте также:  Rtf to html mac

First, create the following folders and files:

├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php Code language: JavaScript (javascript)

Second, place the following code in the header.php file:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link rel="stylesheet" href="css/style.css"> title>PHP select option title> head> body class="center"> main>Code language: HTML, XML (xml)

Third, place the following code in the footer.php file:

 main> body> html>Code language: HTML, XML (xml)

Fourth, add the following code to the get.php file to create a form that has one element with a submit button:

form action="" method="post"> div> label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select> div> div> button type="submit">Select button> div> form>Code language: HTML, XML (xml)

The form uses the POST method to submit data to the webserver.

Finally, add the following code to the post.php file:

 $color = filter_input(INPUT_POST, 'color', FILTER_SANITIZE_STRING); ?>  if ($color) : ?> p>You selected span style="color:"> echo $color ?> span> p> p>a href="index.php">Back to the form a> p>  else : ?> p>You did not select any color p>  endif ?>Code language: HTML, XML (xml)

To get the selected value of the element, you use the $_POST superglobal variable if the form method is POST and $_GET if the form method is GET .

Alternatively, you can use the filter_input() function to sanitize the selected value.

If you select the first option of the element, the selected value will be empty. Otherwise, the selected value is red, green, or blue.

Select with multiple options

To enable multiple selections, you add the multiple attribute to the element:

select name="colors[]" id="colors" multiple> . select>Code language: HTML, XML (xml)

When you select multiple options of a element and submit the form, the name will contain multiple values rather than a single value. To get multiple selected values, you add the square brackets ( []) after the name of element.

Let’s take a look at an example of using a element with multiple selections.

First, create the following folders and files:

. ├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.phpCode language: JavaScript (javascript)

Second, place the following code into the header.php file:

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>PHP Listbox title> link rel="stylesheet" href="css/style.css"> head> body class="center"> main>Code language: HTML, XML (xml)

Third, add the following code to the footer.php file:

 main> body> html>Code language: HTML, XML (xml)

Fourth, include the header.php and footer.php files in the index.php :

 require __DIR__ . '/inc/header.php'; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') < require __DIR__ . '/inc/get.php'; > elseif ($request_method === 'POST') < require __DIR__ . '/inc/post.php'; > require __DIR__ . '/inc/footer.php'; Code language: HTML, XML (xml)

If the HTTP request is GET, the index.php file will show a form from the get.php file. When the form is submitted, the post.php file will handle the form submission.

Fifth, create a form that contains a element with the multiple attribute in the get.php file. The name of the element has an opening and closing square bracket [] so that PHP can create an array that holds the select values.

form action="" method="post"> div> label for="colors">Background Color: label> select name="colors[]" id="colors" multiple> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> option value="purple">Purple option> option value="magenta">Magenta option> option value="cyan">Cyan option> select> div> div> button type="submit">Submit button> div> form>Code language: HTML, XML (xml)

Finally, handle the form submission in the post.php file:

 $selected_colors = filter_input( INPUT_POST, 'colors', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ); ?>  if ($selected_colors) : ?> p>You selected the following colors: p> ul>  foreach ($selected_colors as $color) : ?> li style="color:"> echo $color ?> li>  endforeach ?> ul> p> p>  else : ?> p>You did not select any color. p>  endif ?> a href="index.php">Back to the form a>Code language: HTML, XML (xml)

The post.php file uses the filter_input() function to get the selected colors as an array. If you select one or more colors, the post.php file will display them.

Summary

  • Use the element to create a dropdown list.
  • Use the multiple attribute to create a list that allows multiple selections.
  • Use $_POST to get the selected value of the select element if the form method is POST (or $_GET if the form method is GET ).
  • Add square brackets( [] ) after the name of the element to get multiple selected values.

Источник

array_values

array_values() returns all the values from the array and indexes the array numerically.

Parameters

Return Values

Returns an indexed array of values.

Examples

Example #1 array_values() example

The above example will output:

See Also

  • array_keys() — Return all the keys or a subset of the keys of an array
  • array_combine() — Creates an array by using one array for keys and another for its values

User Contributed Notes 6 notes

Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the ‘foreach’ ordering:

print_r ( array_values ( $a ));
==>
Array(
[ 0 ] => 11
[ 1 ] => 22
[ 2 ] => 33
[ 3 ] => 44
)
?>

Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

For example, if your PHP momory_limits is 8MB,
and says there’s a BIG array $bigArray which allocate 5MB of memory.

Doing this will cause PHP exceeds the momory limits:

$bigArray = array_values ( $bigArray );
?>

It’s because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.

This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
/**
* Get all values from specific key in a multidimensional array
*
* @param $key string
* @param $arr array
* @return null|string|array
*/
function array_value_recursive ( $key , array $arr ) $val = array();
array_walk_recursive ( $arr , function( $v , $k ) use( $key , & $val ) if( $k == $key ) array_push ( $val , $v );
>);
return count ( $val ) > 1 ? $val : array_pop ( $val );
>

$arr = array(
‘foo’ => ‘foo’ ,
‘bar’ => array(
‘baz’ => ‘baz’ ,
‘candy’ => ‘candy’ ,
‘vegetable’ => array(
‘carrot’ => ‘carrot’ ,
)
),
‘vegetable’ => array(
‘carrot’ => ‘carrot2’ ,
),
‘fruits’ => ‘fruits’ ,
);

var_dump ( array_value_recursive ( ‘carrot’ , $arr )); // array(2) < [0]=>string(6) «carrot» [1]=> string(7) «carrot2» >
var_dump ( array_value_recursive ( ‘apple’ , $arr )); // null
var_dump ( array_value_recursive ( ‘baz’ , $arr )); // string(3) «baz»
var_dump ( array_value_recursive ( ‘candy’ , $arr )); // string(5) «candy»
var_dump ( array_value_recursive ( ‘pear’ , $arr )); // null
?>

Most of the array_flatten functions don’t allow preservation of keys. Mine allows preserve, don’t preserve, and preserve only strings (default).

// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) foreach ($array as $key => $child) if (is_array($child)) $newArray =& array_flatten($child, $preserve_keys, $newArray);
> elseif ($preserve_keys + is_string($key) > 1) $newArray[$key] = $child;
> else $newArray[] = $child;
>
>
return $newArray;
>

echo ‘var_dump($array);’.»\n»;
var_dump($array);
echo ‘var_dump(array_flatten($array, 0));’.»\n»;
var_dump(array_flatten($array, 0));
echo ‘var_dump(array_flatten($array, 1));’.»\n»;
var_dump(array_flatten($array, 1));
echo ‘var_dump(array_flatten($array, 2));’.»\n»;
var_dump(array_flatten($array, 2));
?>

If you are looking for a way to count the total number of times a specific value appears in array, use this function:

function array_value_count ( $match , $array )
<
$count = 0 ;

foreach ( $array as $key => $value )
<
if ( $value == $match )
<
$count ++;
>
>

return $count ;
>
?>

This should really be a native function of PHP.

/**
flatten an arbitrarily deep multidimensional array
into a list of its scalar values
(may be inefficient for large structures)
(will infinite recurse on self-referential structures)
(could be extended to handle objects)
*/
function array_values_recursive ( $ary )
$lst = array();
foreach( array_keys ( $ary ) as $k ) $v = $ary [ $k ];
if ( is_scalar ( $v )) $lst [] = $v ;
> elseif ( is_array ( $v )) $lst = array_merge ( $lst ,
array_values_recursive ( $v )
);
>
>
return $lst ;
>
?>

code till dawn! -mark meves!

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

Оцените статью