Welcome Guest, Not a member yet? Register   Sign In
Weird problem with If vs ternary operator unexpected results
#1

[eluser]edjon2000[/eluser]
Hi all Smile

This is a peculiar problem I have come across, where some code should work, but does not.

First of all I am using CI 2.1.0 and have been using this to create a recruitment website for a client.

I have recently been asked to provide a Mass Email type feature on this site so his recruitment clients
can all be informed of new prospects when they become available.

In order to keep things simple for him, it tends to make the coding more difficult for me lol (always the case).

So, in summary, the sequence of actions required to send these emails work like this:-

From admin page mass emails section, choose "select clients", this generates a page with a search form that has the client-specific search fields and some instructions, details are entered into this form (e.g. Location: Manchester) and submitted, this in turn generates a table of results detailing the clients that match the search criteria along with an additional field which is a simple dropdown menu with the options Yes or No(default is yes) to further fine-tune the returned results(i.e. to determine whether or not to include a specific client within the returned results on the email list or not.

As there is a form field(the dropdown list) the whole table is enclosed in form tags and once that is submitted it passes an array of results via $_POST back to the controller which, in turn is converted to a simple $post array using
Code:
$post = $_POST
and then passed to the model, from there, it determines actual fields from the default, when the initial search form loads the fields are set to, in this case, All Names, All Sectors, All Locations, All Phone Numbers, All Postcodes so if you just click Submit, All Client Results are returned, when all of this hits the model, it needs to determine actual search parameters but ignore any fields that have not been changed(i.e. equal to All - whatever)

So part of the code I used in the model looks like this:-
Code:
/**
   * Client data fields
   */
  function client_search($post = array())
  {
    $id = $post['id'];

    #$name = ($post['name'] === 'All Companies') ? '' : $post['name'];

    #echo 'Name - ' . $name; exit();

    $name = $post['name'];
    if ($name == 'All Companies')
    {
      $post['name'] = '';
    }


    #$sector = ($post['sector'] === 'All Sectors') ? '' : $post['sector'];


    $sector = $post['sector'];
    if ($sector == 'All Sectors')
    {
      $post['sector'] = '';
    }


    #$location = ($location === 'All Locations') ? '' : $post['location'];


    $location = $post['location'];
    if ($location == 'All Locations')
    {
      $post['location'] = '';
    }


    #$phone = ($post['first_contact_phone'] === 'All Phone Numbers') ? '' : $post['first_contact_phone'];


    $phone = $post['first_contact_phone'];
    if ($phone == 'All Phone Numbers')
    {
      $post['first_contact_phone'] = '';
    }


    #$postcode = ($post['postcode'] == 'All Postcodes') ? '' : $post['postcode'];


    $postcode = $post['postcode'];
    if ($postcode == 'All Postcodes')
    {
      $post['postcode'] = '';
    }
As you can see I have already tried to implement ternary equations to replace the if statements but as they did not work I commented them out, now, in theory the alternate ternary equations would have been an ideal replacement and should have worked but they didn't, any ideas on this subject would be most appreciated.

I apologise for the long initial post but hopefully it will make any follow-up posts a bit clearer

Jon

#2

[eluser]Samus[/eluser]
I know CI user guide recommends we use '===' rather than '==', but within my apps i've always found that '==' never gives me problems.

Try it out and see if that fixes your problem

EDIT: Upon further research i've found this article:

http://www.jonlee.ca/the-triple-equals-in-php/

Have a read, it makes good sense of when to use == vs ===
#3

[eluser]edjon2000[/eluser]
Hi Samus Smile thank you for for response,

I already tried out "==" and that did not work either

What actually happens is that I get 0 results.

I bet it is a simple syntax error, but, I cannot see it :-S

Jon
#4

[eluser]Samus[/eluser]
[quote author="edjon2000" date="1333839345"]Hi Samus Smile thank you for for response,

I already tried out "==" and that did not work either

What actually happens is that I get 0 results.

Jon[/quote]
My bad then.

You could probably enable profiler to help in your debugging and check if anything's actually coming in the post.

Just an idea..
#5

[eluser]edjon2000[/eluser]
Hey Samus,

No need to say "my bad" I appreciate any responses from the community Smile

It's just a strange problem that shouldn't really happen, this site started off as a simple project and has now become massive but, at the end of the day, I want to be able to make websites that are user friendly and I have found that CI deals with a lot of things in the background.

Jon
#6

[eluser]InsiteFX[/eluser]
That's because === only checks for true boolean TRUE or FALSE unlike == that check for equal to!

change your code to == and it should work!
#7

[eluser]Aken[/eluser]
There's nothing wrong with your ternary functions. Which means there's something wrong with the data.

Try to var_dump your $post array in the function and see what's ACTUALLY being passed. Because if you're expecting one thing and getting another, then you might think something else is the problem.
#8

[eluser]edjon2000[/eluser]
Hi InsiteFX,

[quote author="InsiteFX" date="1333855295"]That's because === only checks for true boolean TRUE or FALSE unlike == that check for equal to!

change your code to == and it should work!
[/quote]

Yes thats quite right "==" means "equal to" and "===" means "exactly equal to" the ternary operator is essentially a simple logical switch
Code:
$phone = ($post['first_contact_phone'] === 'All Phone Numbers') ? '' : $post['first_contact_phone'];
in this case, should the field $post[first_contact_phone] contain the exact wording "All Phone Numbers", this equates to true and the true branch of the equation is followed the part between the ? and the : which should set the $phone variable to an empty string otherwise the false branch of the equation is followed which sets $phone to $post['first_contact_phone'] for subsequent use as the WHERE part of the query is built in the next section of code.

@Aken for this example I have only filled in the phone number field
Code:
<pre>Contents of the $post array BEFORE processing => array(6) {
  ["id"] => string(0) ""
  ["name"] => string(13) "All Companies"
  ["sector"] => string(11) "All Sectors"
  ["location"] => string(13) "All Locations"
  ["first_contact_phone"] => string(6) "123456"
  ["postcode"] => string(13) "All Postcodes"
}
</pre>

<pre>Contents of the $post array AFTER processing => array(6) {
  ["id"] => string(0) ""
  ["name"] => string(0) ""
  ["sector"] => string(0) ""
  ["location"] => string(0) ""
  ["first_contact_phone"] => string(6) "123456"
  ["postcode"] => string(0) ""
}
</pre>

This is using the if sections of code rather than the ternary equations and it appears to work as expected.

This is using the ternary equations with "=="
Code:
<pre>Contents of the $post array BEFORE processing => array(6) {
  ["id"] => string(0) ""
  ["name"] => string(13) "All Companies"
  ["sector"] => string(11) "All Sectors"
  ["location"] => string(13) "All Locations"
  ["first_contact_phone"] => string(6) "123456"
  ["postcode"] => string(13) "All Postcodes"
}
</pre>

<pre>Contents of the $post array AFTER processing => array(6) {
  ["id"] => string(0) ""
  ["name"] => string(13) "All Companies"
  ["sector"] => string(11) "All Sectors"
  ["location"] => string(13) "All Locations"
  ["first_contact_phone"] => string(6) "123456"
  ["postcode"] => string(13) "All Postcodes"
}
</pre>
It would seem that the ternary equations are always returning false

Jon
#9

[eluser]edjon2000[/eluser]
Just for an example I switched the equation about as follows:-
This is the original equation
Code:
$name = ($post['name'] == 'All Companies') ? '' : $post['name'];
    $sector = ($post['sector'] == 'All Sectors') ? '' : $post['sector'];
    $location = ($post['location'] == 'All Locations') ? '' : $post['location'];
    $phone = ($post['first_contact_phone'] == 'All Phone Numbers') ? '' : $post['first_contact_phone'];
    $postcode = ($post['postcode'] == 'All Postcodes') ? '' : $post['postcode'];
and this is the switched version
Code:
$name = ($post['name'] !== 'All Companies') ? $post['name'] : '';
    $sector = ($post['sector'] !== 'All Sectors') ? $post['sector'] : '';
    $location = ($post['location'] !== 'All Locations') ? $post['location'] : '';
    $phone = ($post['first_contact_phone'] !== 'All Phone Numbers') ? $post['first_contact_phone'] : '';
    $postcode = ($post['postcode'] !== 'All Postcodes') ? $post['postcode'] : '';
all that actually happened is that all the equations returned true as opposed to false, and still didn't work.

As there is a bit of a time constraint on this particular project I will use the if versions for now - I know that they aren't pretty but they do work.

I mentioned earlier that the results of these equations contribute to the WHERE clause of the database query, so, to give you an idea of where I was aiming to go, here is the full model method
Code:
/**
   * Client data fields
   */
  function client_search($post = array())
  {
    $id = $post['id'];

    #dump($post, 'Contents of the $post array BEFORE processing'); #exit();

    $name = $post['name'];
    if ($name == 'All Companies')
    {
      $post['name'] = '';
    }

    $sector = $post['sector'];
    if ($sector == 'All Sectors')
    {
      $post['sector'] = '';
    }

    $location = $post['location'];
    if ($location == 'All Locations')
    {
      $post['location'] = '';
    }

    $phone = $post['first_contact_phone'];
    if ($phone == 'All Phone Numbers')
    {
      $post['first_contact_phone'] = '';
    }

    $postcode = $post['postcode'];
    if ($postcode == 'All Postcodes')
    {
      $post['postcode'] = '';
    }

/*
    $name = ($post['name'] == 'All Companies') ? '' : $post['name'];
    $sector = ($post['sector'] == 'All Sectors') ? '' : $post['sector'];
    $location = ($post['location'] == 'All Locations') ? '' : $post['location'];
    $phone = ($post['first_contact_phone'] == 'All Phone Numbers') ? '' : $post['first_contact_phone'];
    $postcode = ($post['postcode'] == 'All Postcodes') ? '' : $post['postcode'];
*/

/*
    $name = ($post['name'] !== 'All Companies') ? $post['name'] : '';
    $sector = ($post['sector'] !== 'All Sectors') ? $post['sector'] : '';
    $location = ($post['location'] !== 'All Locations') ? $post['location'] : '';
    $phone = ($post['first_contact_phone'] !== 'All Phone Numbers') ? $post['first_contact_phone'] : '';
    $postcode = ($post['postcode'] !== 'All Postcodes') ? $post['postcode'] : '';
*/

    #dump($post, 'Contents of the $post array AFTER processing'); exit();


    // Determine searchable fields:
    $fields = array_keys($post);

    // Start query:
    $this->db->select();

    // Loop through searchable fields:
    foreach ($fields as $field)
    {
      // If the field is set and not empty:
      if (isset($post[$field]) && $post[$field] != '')
      {
        // Create a new condition while escaping the inputted values (SQL injection):
        $this->db->like($field, $post[$field]);
      }
    }

    $this->db->order_by('name');

    $query = $this->db->get('tbl_clients');

    #echo $this->db->last_query(); #exit();

    #dump($query->result(), 'Query Result:'); exit();

    return $query->result();
  }
Please excuse all of the commented out sections.

I would like to thank you all for your help, I really appreciate it, and, I am sure, I will have a few more dumb questions further down the line Smile

Jon.
#10

[eluser]Aken[/eluser]
[quote author="edjon2000" date="1333870400"]This is using the ternary equations with "=="
Code:
<pre>Contents of the $post array BEFORE processing => array(6) {
  ["id"] => string(0) ""
  ["name"] => string(13) "All Companies"
  ["sector"] => string(11) "All Sectors"
  ["location"] => string(13) "All Locations"
  ["first_contact_phone"] => string(6) "123456"
  ["postcode"] => string(13) "All Postcodes"
}
</pre>

<pre>Contents of the $post array AFTER processing => array(6) {
  ["id"] => string(0) ""
  ["name"] => string(13) "All Companies"
  ["sector"] => string(11) "All Sectors"
  ["location"] => string(13) "All Locations"
  ["first_contact_phone"] => string(6) "123456"
  ["postcode"] => string(13) "All Postcodes"
}
</pre>
It would seem that the ternary equations are always returning false

Jon[/quote]

They're not returning false, they're working just as they should. The $post array is not changing because you are not modifying the $post array when using the ternary operations. You are creating and assigning values to new variables.




Theme © iAndrew 2016 - Forum software by © MyBB