Exclude or include with PHP in_array

PHP in_array function is very helpful if you want to include or exclude php code of files based on a certain criteria like id’s or $_GET variables.

Let’s imagine that you have a list of numbers that we want to use to include a file.

  1. <?php
  2. $list = array(1,5,10);
  3. $id = 1; // set $id to a value from the array
  4.  
  5. if(in_array($id, $list)) { // check if is in array with in_array(what, in what);
  6.  include('file.php');
  7. }
  8. else {
  9.  echo "The number is not in the array";
  10. }
  11. ?>

If you want the get the page id or some parameter from the url using $_GET variable use the code snippet below and display content based on the id’s value.



Let’s imagine that we have an url like /index.php?id=6.
Because we have number 6 in the array() and by using the php code below it will echo SHOW CONTENT and if we have an url like /index.php?id=2 (2 is not in the array()) it will echo EXCLUDE CONTENT BECAUSE ID IS NOT IN THAT ARRAY.

  1. <?php
  2. $id = $_GET['id'];
  3. if(isset($id)) { // if we set the id parameter in the url
  4. $list = array(1,3,6,10,22);
  5. if(!in_array($id, $list)) { // if is not in array (!in_array)
  6.  echo "EXCLUDE CONTENT BECAUSE ID IS NOT IN THAT ARRAY";
  7. }
  8. else {
  9.  echo "SHOW CONTENT";
  10. }
  11. }
  12. ?>

No related php tutorials.

bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark
tabs-top

One Response to “Exclude or include with PHP in_array”

  1. birat says:

    this web site too good for me
    plz cont it……….

Leave a Reply