Welcome Guest, Not a member yet? Register   Sign In
check array for values that match
#1

[eluser]Brad K Morse[/eluser]
I have a form that will store three items into an array.

I want to check those items and make sure all three are different values, if there is a match, I want to return FALSE;

example array:

Code:
$fruit = array('apple', 'orange', 'apple');

// compare each item in array, if match is found, return TRUE

return FALSE;

$fruit = array('apple', 'orange', 'banana');

// compare each item in array, if no match is found, return FALSE

return TRUE;

I am not sure how I would check each item in the array - any help is appreciated, thanks.

UPDATE: created three different drop-down fields, and just did a conditional, not sure if that is the most efficient way to accomplish it.

I don't need it to be in an array, I would actually prefer it being in 3 separate drop-downs.

Code:
// form submitted and validated continue processing
if($this->input->post('register') && $this->form_validation->run())    {
    // if user selects the same venue twice, let them know
    if(
        ( $this->input->post('venue_1') == $this->input->post('venue_2') )
            ||
        ( $this->input->post('venue_1') == $this->input->post('venue_3') )
            ||
        ( $this->input->post('venue_2') == $this->input->post('venue_3') )
    ) {
        $data['duplicate_venue_error'] = "Each preference needs to be different";
        $this->load->view('register/registration-form-view', $data);
    } else {
        // each venue was different, proceed
        // form validated and worked, go insert volunteer info into data table
        $this->register_model->insertVolunteer();
    }
} else {
    $data['duplicate_venue_error'] = NULL;    // pass null to shut up undefined variable msg in view
    $this->load->view('register/registration-form-view', $data);
}
#2

[eluser]Federico BaƱa[/eluser]
you sort the array and iterate through:

Code:
$arr = array('asd', 'bsd', 'dsd', 'csd', 'csd');

asort($arr); // get asd, bsd, csd, csd, dsd

$i = count($arr);
while ($i--)
{
    if ($arr[$i] === $arr[$i - 1])
    {
        return FALSE;
    }
}
return TRUE;

// You get FALSE as you have 2 "csd" values
#3

[eluser]Atharva[/eluser]
Code:
$arr = array('asd', 'bsd', 'dsd', 'csd', 'csd');
$result = array_unique($arr);

if(count($arr) != count($result))//this means there are some duplicates
return false;// or true or whatever
#4

[eluser]Madmartigan1[/eluser]
Most simple way:

Code:
if (array_unique($array) !== $array) return false;




Theme © iAndrew 2016 - Forum software by © MyBB