Page 166 - Open Soource Technologies 304.indd
P. 166

Web Technologies-I



                   Notes                Example:

                                 $addresses = array(‘spam@cyberpromo.net’,

                                 ‘abuse@example.com’, ‘root@example.com’);
                                 $got_spam = in_array(‘spam@cyberpromo.net’,
                                 $addresses);
                                 // $got_spam is true $got_milk = in_array(‘milk@tucows.com’, $addresses); // $got_milk is false

                                 PHP automatically indexes the values in arrays, so in_array( ) is much faster than a loop that
                                 checks every value to find the one you want.

                                 Example checks whether the user has entered information in all the required fields in a form.
                                               Searching an array

                                 <?php
                                 function have_required($array , $required_fields) {
                                 foreach($required_fields as $field) {

                                 if(empty($array[$field])) return false;
                                  }  return true;
                                 }

                                 if($submitted) {
                                 echo ‘<p>You ‘;
                                 echo have_required($_POST, array(‘name’, ‘email_address’)) ? ‘did’ : ‘did not’;

                                 echo ‘ have all the required fields.</p>’;
                                 } ?>
                                 <form action=”<?= $PHP_SELF; ?>” method=”POST”>

                                 <p>
                                 Name: <input type=”text” name=”name” /><br />
                                 Email address: <input type=”text” name=”email_address” /><br />

                                  Age (optional): <input type=”text” name=”age” />
                                 </p>
                                  <p align=”center”> <input type=”submit” value=”submit” name=”submitted” /> </p>

                                 </form>
                                 A variation on in_array( ) is the array_search( ) function. While in_array( ) returns true if the
                                 value is found, array_search( ) returns the key of the found element:
                                 $person = array(‘name’ => ‘Pradip’, ‘age’ => 35, ‘wife’ => ‘Riya’);
                                 $k = array_search($person, ‘Riya’);
                                 echo(“Pradip’s $k is Riya\n”);

                                 Pradip’s wife is Riya



        160                               LOVELY PROFESSIONAL UNIVERSITY
   161   162   163   164   165   166   167   168   169   170   171