Jump to content


This topic is now archived and is closed to further replies.


problems with arrays

Recommended Posts

hi, i've been on this for hours now and wondering if anyone can help me.

i'm trying to loop through the array below in order to remove any elements which don't  return a 'true' value when i $post them. i do this using unset.

if i echo out an element whilst in the loop, it echos out the right data. howver when i call the array after the end of the loop- the element which i unset magically reapeears. hoorah!  ::)

[code]$chkbox_arr = array ( 'dj', 'liveMusic', 'nsArea','food','skySport', 'cocktails'
            ,'pool', 'garden', 'lateLice', 'kidsZone' );
  for ( $i = 0; $i <10; $i++ )
    $element = $chkbox_arr[$i];
    $chkbox_value = $_POST[$element];
    if ($chkbox_value != 'true')
  for ( $i = 0; $i <11; $i++ )
    echo "$chkbox_arr[$i]  ";[/code]

Share this post

Link to post
Share on other sites
What you're unsetting there is just a local variable.. instead use


That will remove element $i from the array.  Keep in mind that the array will not be renumbered when you do this.. so for your loop afterwards you can do

[code]foreach ($chkbox_arr as $element) {
  echo "$element  ";

That removes the dependence on having the array indexed consecutively by numbers.

Also try var_dump($chkbox_arr) to see what your array looks like at the end.

Share this post

Link to post
Share on other sites
Only checked checkboxes are POSTed, so if design the form like this below, naming all the checkboxes "chkbox[]", then the array you are try to end up with will be the array of c/box values.

// checkboxes sent as an array
// only check ones are sent
if (isset ($_POST['chkbox']) )  {
    echo 'You selected<ol>' ;
    foreach ($_POST['chkbox'] as $value) {
        echo '<li>' . $value . '</li>';
    echo '</ol>' ;
<form method='post'>
    <input type="checkbox" name="chkbox[]" value="dj"> dj<br />
    <input type="checkbox" name="chkbox[]" value="liveMusic"> liveMusic<br />
    <input type="checkbox" name="chkbox[]" value="nsArea"> nsArea<br />
    <input type="checkbox" name="chkbox[]" value="food"> food<br />
    <input type="checkbox" name="chkbox[]" value="skySport"> skySport<br />
    <input type="checkbox" name="chkbox[]" value="cocktails"> cocktails<br />
    <input type="checkbox" name="chkbox[]" value="pool"> pool<br />
    <input type="checkbox" name="chkbox[]" value="garden"> garden<br />
    <input type="checkbox" name="chkbox[]" value="lateLice"> lateLice<br />
    <input type="checkbox" name="chkbox[]" value="kidsZone"> kidsZone<br />

    <input type="submit" name="action" value="Submit">

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.