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.
-
<?php
-
$list = array(1,5,10);
-
$id = 1; // set $id to a value from the array
-
-
if(in_array($id, $list)) { // check if is in array with in_array(what, in what);
-
include('file.php');
-
}
-
else {
-
echo "The number is not in the array";
-
}
-
?>
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.
-
<?php
-
$id = $_GET['id'];
-
if(isset($id)) { // if we set the id parameter in the url
-
$list = array(1,3,6,10,22);
-
if(!in_array($id, $list)) { // if is not in array (!in_array)
-
echo "EXCLUDE CONTENT BECAUSE ID IS NOT IN THAT ARRAY";
-
}
-
else {
-
echo "SHOW CONTENT";
-
}
-
}
-
?>
this web site too good for me
plz cont it……….