Key Your
Key Your
![]() |
Php 101: Php Finding Keys Within Sessions Using Isset() And_Key_Exists()
PHP 101: PHP FINDING KEYS WITHIN SESSIONS USING ISSET() AND ARRAY_KEY_EXISTS()
Written by: Robert Guida, guidaMedia.com, ©2009.
The isset function is a staple utility of PHP to make sure sessions variables exist before accessing them. Unless you are familiar with session variables, even after reading about them on php.net, this lesson will help you gain a better understanding on how to check the existence of a session key.
We will test different uses of isset to see the results. Some you may expect, while others may surprise you. After looking at isset the lesson tests array_key_exists, to show how the function can be utilized in your code. We will look at simple single-depth sessions and multi-dimension sessions. By single-depth session I am referring to a session key that is at the first level, $_SESSION["key"]. I also refer to this key as a parent key, as it can have a sub-key, like $_SESSION["key"]["sub-key"]. I refer to the sub-key as a child key. This is also what I mean by a mult-dimension session, as it has multiple layers.
Just a few notes about the tests: The full test is at the end of the article. You can copy and paste that into you editor and run it. You can also run each test separately. Running the full script provides formatting to easily review the results, while the individual test do not. You will notice that I provide two results for each test, however, only one is possible. I do this because I take more of an experimental approach to explaining the differences to provide a definitive understanding of how to access session keys.
Last note: We are testing sessions, so if you do not already know, this remains set until your session ends; when you close your browser. To avoid having to close the browser a unset function is included, so the key in the session is dropped.
Test 1
This first test examines the typical use of isset. However, test 1a uses isset with a session key that is not set, and 1b sets the key and runs the same test.
echo "
Test 1a: Testing ISSET on a key at the first level. The key is not set.
";
if(isset($_SESSION["PHP_SESSION"])){
echo "
Yes, the key PHP is set, however it was never set.
";
}else{
echo "
No, the key PHP is not set.
";
}
echo "
Test 1b: Testing ISSET on a key at the first level. The key is set.
";
$_SESSION["PHP_SESSION"] = "5";
if(isset($_SESSION["PHP_SESSION"])){
echo "
Yes, the key PHP is set.
";
}else{
echo "
No, the key PHP is not set, however it is set.
";
}
unset($_SESSION["PHP_SESSION"]);
The results work as you probably expect. Test 1a returns "No", while 1b returns "Yes". 1a returns "No" because we have not yet set the key "PHP_SESSION". When it is set for 1b, isset finds the key is set.
So, let's continue testing, and see what happens when use isset with a child key that has a value.
Test 2
In this test we look at the results of using ISSET on a child key. We test if the child key is set, as well, if it is not set. Here again we get some expected results.
echo "
Test 2a: Testing ISSET on a child key. The child key is set.
";
$_SESSION["PHP_SESSION"]["ISSET"] = "Setting the child key, 'PHP SESSION ISSET'";
if(isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
Yes, it appears the child key is set. The result is the same as test 2a.
";
}else{
echo "
The result is false.
";
}
echo "
Test 2b: Testing NOT ISSET on a child key. The child key is set.
";
if(!isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
The result is false.
";
}else{
echo "
Yes, it appears the child key is set. The result is the same as test 2b.
";
}
unset($_SESSION["PHP_SESSION"]);
Test 2a results in "Yes", and so does test 2b. This is expected. So why test if not isset? To answer this, lets look at Test 3, and mix it up a little.
Test 3
This test uses the same tests from Test 2, but we unset the child key. Let see what our results are.
echo "
Test 3a: Testing ISSET on a child key. The child key is not set.
";
$_SESSION["PHP_SESSION"] = "Setting the parent key PHP SESSION";
if(isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
Yes, it appears the child key is set.
";
}else{
echo "
The result is false.
";
}
echo "
Test 3b: Testing NOT ISSET on a child key. The child key is not set.
";
if(!isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
The result is false.
";
}else{
echo "
Yes, it appears the child key is set.
";
}
unset($_SESSION["PHP_SESSION"]);
The results we get in test 3 are the same as test 2. Why is this? Let's look at the definition of the isset function from php.net:
"Evaluation goes from left to right and stops as soon as an unset variable is encountered."
What this means is, the isset function checks the parent key, then it looks for the child key, which is to the right of the parent. Thus, it looks left to right. Since the child key is not set, the search stops, and the isset value for the parent key is returned rather than the child. Since the parent value is set, the result is "true".
Test 2 and 3 shows us that using isset on a child key is not reliable, since the results you get are the same when it is set, as when it is not? This is where array_key_exists come in to the rescue.
Again, to ensure you have a definitive understanding of array_key_exists, we examine different uses of this function. Once done, you should know how to use array_key_exists.
Test 4
This test looks at using array_key_exists on a parent key, and then a child key.
echo "
Test 4a: Testing ARRAY_KEY_EXISTS on a parent key. The parent key is set.
";
$_SESSION["PHP_SESSION"]["AKE"] = "Setting the child key, 'PHP SESSION AKE'";
if(array_key_exists("PHP_SESSION", $_SESSION)){
echo "
Yes, the parent key exists.
";
}else{
echo "
The result is false.
";
}
echo "
Test 4b: Testing ARRAY_KEY_EXISTS on a child key. The child key is set.
";
if(array_key_exists("AKE", $_SESSION)){
echo "
The result is true, but ISSET does not exist at the parent key level.
";
}else{
echo "
No, the child key does not exists because we are searching the wrong level.
";
}
Test 4a returns true, while test 4b doesn't. In order to find the child key, the session and the parent key, $_SESSION["PHP_SESSION"], must be used in the search. The next test shows us how to successfully use array_key_exists.
Test 5
This example shows how to test the session for a child key. By including the parent key in the search, we find the child key.
echo "
Test 5: Testing ARRAY_KEY_EXISTS on a child key, using the parent key in the search. The child key is set.
";
if(array_key_exists("AKE", $_SESSION["PHP_SESSION"])){
echo "
Yes, the child key exists, because we are searching the parent key, PHP SESSION.
";
}else{
echo "
The result is false.
";
}
$string = "This is a string to see the results when isset and array_key_exists are used on non array type variables, such as
a string.";
echo "
Test 6a: What happens when we use isset on a string.
";
if(isset($string)){
echo "
The variable is set.
";
}else{
echo "
The result is false.
";
}
echo "
Test 6b: What happens when we use array_key_exists on a string.
";
if(array_key_exists("results", $string)){
echo "
The variable is set.
";
}else{
echo "
The result is false. This will result in an error if error_reporting is not set to zero.
";
}
The result: "Yes". As mentioned, since the parent key is used in the search, the child is found. By adding the parent key, it directs the function to search inside the key.
So, now you may be wondering, what to use, array_key_exists, or isset. It really comes down to efficiency, reliability and choice. See, if you think for consistency sake using array_key_exists is the right choice, there are a few things to challenge that. One is, it appears the industry standard to use is isset. At least in all the code I have seen and worked with, that is the case. So there is a reason for that.
Could it be that if you end up passing a string into an array_key_exists function that the following error will be generated?
Warning: array_key_exists() [function.array-key-exists]: The second argument should be either an array or an object in Testing_ISSET_AKE_on_SESSIONS.php on line 95
That alone may be a good reason not to solely use array_key_exists. Isset does not throw an error. This test is included in the complete test at the end of the article.
I personally am used to using isset, because it is much easier to type. The only times I uses array_key_exists is when I am testing a child key. My formula, and my conclusion to this lesson is, I use isset whenever possible, but as soon as I need to test a child key, I use array_key_exists.
I hope this has helped you.
Here is the full testing code, or click here to go the actual PHP code.
<!--CTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--p
echo "
PHP FINDING KEYS WITHIN SESSIONS USING
ISSET() AND ARRAY_KEY_EXISTS()
";
error_reporting(0);
echo "
Test 1a: Testing ISSET on a key at the first level. The key is not set.
";
if(isset($_SESSION["PHP_SESSION"])){
echo "
Yes, the key PHP is set, however it was never set.
";
}else{
echo "
No, the key PHP is not set.
";
}
echo "
Test 1b: Testing ISSET on a key at the first level. The key is set.
";
$_SESSION["PHP_SESSION"] = "5";
if(isset($_SESSION["PHP_SESSION"])){
echo "
Yes, the key PHP is set.
";
}else{
echo "
No, the key PHP is not set, however it is set.
";
}
unset($_SESSION["PHP_SESSION"]);
echo "
Test 2a: Testing ISSET on a child key. The child key is set.
";
$_SESSION["PHP_SESSION"]["ISSET"] = "Setting the child key, 'PHP SESSION ISSET'";
if(isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
Yes, it appears the child key is set. The result is the same as test 2a.
";
}else{
echo "
The result is false.
";
}
echo "
Test 2b: Testing NOT ISSET on a child key. The child key is set.
";
if(!isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
The result is false.
";
}else{
echo "
Yes, it appears the child key is set. The result is the same as test 2b.
";
}
unset($_SESSION["PHP_SESSION"]);
echo "
Test 3a: Testing ISSET on a child key. The child key is not set.
";
$_SESSION["PHP_SESSION"] = "Setting the parent key PHP SESSION";
if(isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
Yes, it appears the child key is set.
";
}else{
echo "
The result is false.
";
}
echo "
Test 3b: Testing NOT ISSET on a child key. The child key is not set.
";
if(!isset($_SESSION["PHP_SESSION"]["ISSET"])){
echo "
The result is false.
";
}else{
echo "
Yes, it appears the child key is set.
";
}
unset($_SESSION["PHP_SESSION"]);
echo "
Test 4a: Testing ARRAY_KEY_EXISTS on a parent key. The parent key is set.
";
$_SESSION["PHP_SESSION"]["AKE"] = "Setting the child key, 'PHP SESSION AKE'";
if(array_key_exists("PHP_SESSION", $_SESSION)){
echo "
Yes, the parent key exists.
";
}else{
echo "
The result is false.
";
}
echo "
Test 4b: Testing ARRAY_KEY_EXISTS on a child key. The child key is set.
";
if(array_key_exists("AKE", $_SESSION)){
echo "
The result is true, but ISSET does not exist at the parent key level.
";
}else{
echo "
No, the child key does not exists because we are searching the wrong level.
";
}
echo "
Test 5: Testing ARRAY_KEY_EXISTS on a child key, using the parent key in the search. The child key is set.
";
if(array_key_exists("AKE", $_SESSION["PHP_SESSION"])){
echo "
Yes, the child key exists, because we are searching the parent key, PHP SESSION.
";
}else{
echo "
The result is false.
";
}
$string = "This is a string to see the results when isset and array_key_exists are used on non array type variables, such as
a string.";
echo "
Test 6a: What happens when we use isset on a string.
";
if(isset($string)){
echo "
The variable is set.
";
}else{
echo "
The result is false.
";
}
echo "
Test 6b: What happens when we use array_key_exists on a string.
";
if(array_key_exists("results", $string)){
echo "
The variable is set.
";
}else{
echo "
The result is false. This will result in an error if error_reporting is not set to zero.
";
}
error_reporting(E_ALL);
print_r($_SESSION);
unset($_SESSION["PHP_SESSION"]);
?>
About the Author
Robert Guida has more than fifteen years experience in Web Application Development and Multi-Media. Mr. Guida has extensive experience designing and developing Websites, including database-driven Web applications, and as a Graphic Designer developing concepts and images for the Web, interactive multi-media programs, and print. As well, Mr. Guida has served as a trusted partner for clients providing management and consulting services for Web development projects. He also has provided marketing services that included designing and managing outreach efforts for a non-profit organization. Throughout his career, he has helped design, develop, and deploy cutting-edge applications, such as a sophisticated real-time market research tool that handles on-line data collection and reporting and was used by MSNBC and Fox News for the 2000 Vice-Presidential and Presidential Debates and Conventions. His expertise in design resulted in the receipt of an Addy Award, granted for a database-driven kiosk he designed and developed.
|
|
Key To Your Heart $10 Key To Your Heart |
|
|
Cut Your Key $9.49 Cut Your Key |
|
|
The Key to Your Dreams $49.99 The Key to Your Dreams - Giclee Print |
|
|
The Key to Your Dream Home $19.99 The Key to Your Dream Home - Photographic Print |
|
|
Key $9.99 Key Art Print by Kim Klassen. Product size approximately 12 x 12 inches. Available at Art.com. Embrace your Space - your source for high quality fine art posters and prints. |
|
|
The Key $30 The paperback edition of Joe Vitale's inspiring guide to attracting wealth, health, happiness, and more Now available in paperback, inspirational author Joe Vitale's The Key finally reveals the secret to attracting anything you want from life-money, happiness, professional success, love, or anything else. This book goes beyond Vitale's bestselling book The Attractor Factor and the mega-hit movie The Secret to reveal a powerful and effective way to get more out of every aspect of your life. If you know you can achieve more, but can't seem to make it happen, The Key reveals the psychological and unconscious limitations that are holding you back. You'll learn ten proven ways to stop sabotaging yourself and align your conscious and subconscious minds. This book gives you all the personal insight you need to unlock secret doors within yourself and open new opportunities and possibilities in your life. From Joe Vitale, bestselling author of The Attractor Factor, Zero Limits, and Life's Missing Instruction Manual Gives you the guidance and advice you need to unlock your full potential in life Offers practical help for dealing with problems with your job, finances, and any other aspect of your life If you want to be the best you can be, no matter what you do, this book is The Key to unlocking a better, more successful you. |
|
|
Mastering Your Key Accounts $14.95 You rely on your key accounts for repeat business over time, but with Stephan Schiffman's tips and strategies, you'll find out how to increase your sales to these accounts and solidify your relationship as "partners" in the sales process. In Mastering Your Key Accounts, Stephan Schiffman shows you how to implement a winning selling philosophy based on taking calculated risks and stirring things up within existing accounts. He gives you the tools to build key strategic alliances in all of your accounts. Inside you'll find sure-fire strategies to build alliances and win over critical constituents; develop and refine a Major Account Mapping worksheet; devise a growth/action plan for key accounts; finalize an action plan that extends your network within the major account; and much more! As America's recognized #1 sales trainer Stephan Schiffman promises to give you proven advice that will boost your business--and your bottom line! |
|
|
Key to Your Heart Belly Ring $3.99 Key to Your Heart Belly Ring This stainless steel belly ring can be the key to a classy and lovely accent. Unlock your heart with this stylish skeleton key belly ring with a hollow heart top. Specifications: 14 Gauge (1.6mm), 7/16" (11mm), 316L Surgical Grade Stainless Steel, 5mm Ball, Handmade in the USA |
|
|
Key to Your City $35.09 Key 2 Your City offers sound advice for rappers, singers, actors and models to break into the entertainment scene in a major way No matter where you are in the game. Two time author Raheem gives the reader ALL of the game plus some. Combined with years of experience in the industry, Raheem clearly demonstrates stepbystep what you must do to make it to the next level of your career. In fact, Raheem is responsible for the success of many careers, whether providing advice or single handedly securing major deals for his artists. Just to name a few: Ludacris, The Dream, Franchise Boyz (Universal Music), Drama (Atlantic Records), Young Dro, Yola the Great (Atlantic Records) and many more Carry this book with you and use it as your guide, stepbystep until you reach the top Raheems journey is filled with success, happy times and bad. The Atlanta legend puts it down like never before. Author: Raheem, M./ Milton, Argus/ Covington, Christy Binding Type: Paperback Number of Pages: 156 Publication Date: 2010/08/03 Language: English Dimensions: 5.50 x 8.50 x 0.41 inches |
|
|
The Key to Your Church's Vision $14.99 "John Maxwell makes the statement that everything rises and falls on leadership. If that statement is true, doesn't it make sense to focus our prayers on the critical issue that is the true catalyst for achieving God-purposed goals in our churches across the nation and world? In The Key to Your Church's Vision: The Practical Guide to Praying For Your Pastor, Pastor Cameron King unlocks Psalm 45 as the scriptural prayer guide that will direct every praying parishioner into effective prayers for their shepherd. Every chapter will relate to issues that are close to your pastor's heart. When God answers your prayers for your pastor, God's vision for your congregation will begin to be unlocked as your pastor enters into a season of unprecedented accomplishment. Every chapter is jam-packed with scriptural truth that, if prayed, will preserve your pastor and his family while accelerating the work of God in your congregation. This is a MUST READ FOR PEOPLE WHO DESIRE TO SEE THE WILL OF GOD FULLFILLED IN THEIR CONGREGATION Pastor John Cameron King graduated from Southeastern University of the Assembly of God in Lakeland, Florida with a B.A. in Church Ministries with a concentration in preaching. He also holds an M.A. in General Theological Studies from Columbia International University. Under Cameron's pastoral leadership, the Lord re-birthed and has transformed First Assembly of God in Cairo, Georgia from a small, dying church of nine people to a healthy, multicultural congregation that loves ministering to the poor, reaching the unchurched, and being in the presence of God. First Assembly is located in a small poverty-stricken rural community in Southwest Georgia. Cameron is the founder ofCairo First Outreach Center, a nonprofit organization whose mission is to address the practical needs of poverty in Cairo and Grady County." |
|
|
Key To Your Childs Heart $13.99 "A repeat bestseller for two decades, this child-rearing classic cuts to the heart of the anger and alienation that mar so many modern homes. In this ultimately practical book, Gary Smalley outlines effective steps for parents to open up a child that has shut them out. He describes family-tested ways for parents to set limits and enforce them, and he reveals the simple but powerful secret for achieving a close-knit family. Learn proven parenting methods that can spell the difference between an angry, rebellious, distant child and a happy, cooperative one." |
|
|
Psychoanalysis the Key to Your Success $25.14 As an answer to the request of many of his students, the author has gathered the lessons they had studied together and compiled this little book. There is no effort at technical exactness in the formation of the various psychic laws discussed, rather there is a careful attempt to evade all technicalities and to arrive at a comprehensive understanding of the spirit of the laws. Discussions found within are on such topics as repression, written free association, law of love, and inferiority complex. Author: Dukette, Eugene R. Binding Type: Paperback Number of Pages: 56 Publication Date: 2009/12/24 Language: English Dimensions: 5.98 x 9.01 x 0.13 inches |
|
|
The Key to Your Personality $30.9 Kessinger Publishing is the place to find hundreds of thousands of rare and hardtofind books with something of interest for everyone Author: Roth, Charles B. Binding Type: Paperback Number of Pages: 260 Publication Date: 2005/06/23 Language: English Dimensions: 6.00 x 9.00 x 0.59 inches |
|
|
Your Key to Success $25.74 No Synopsis Available |
|
|
The Key to Your Child's Heart $13.64 No Synopsis Available |
|
|
The Key to Your Own Nativity $22.03 No Synopsis Available |
|
|
The Key to Your Desires $11.65 No Synopsis Available |
|
|
Key to your Heart Diamond Pendant $139.99 Key to your Heart Diamond Pendant crafted in 14 kt White Gold Dimensions: Height: 15.50 mm Width: 11.60 mm3 Stones 0.02 Carats Round Diamonds Color: G-H Clarity: SI Made in USA Free 18 inches gold chain included |
|
|
Key Chain $2.95 River Road Key Chain Keep track of your keys with the River Road Key Chain. |
|
|
Who Holds The Key To Your Heart $12.99 "Helping women let God into their "secret place."Inside the hearts of most women lies a "secret place" containing hidden thoughts, painful experiences, and emotions that they feel are better left alone. But God wants to have all of their hearts and desires to set them free from guilt and shame. Lysa TerKeurst offers Who Holds the Key to You Heart? as a practical tool to help women identify their shame and lead them to hope and healing through Scripture. Women will be renewed through a deeper understanding of their identity in Christ and break the bondage hidden in their secret place." |
|
|
Key Fob $1.99 Pro Taper Key Fob Stop losing your keys and?sport your favorite company's logo?with this fashionable key fob. 3-D Double Sided |
|
|
Gibraltar Speed Key Drum Key $3.99 Change your drum heads quickly and easily with this crank-shaped drum key. |
|
|
Communication: Key to Your Marriage (Paperback) $22.95 What does it take to make a marriage intimate, loving and fun? It all starts with communication, the key to a vibrant, happy, lifelong partnership. In this new updated edition of the best-selling classic, trusted marriage and family counselor Dr. Norm Wright doesn`t just show readers the different ways men and women communicate?he shows how to do it right! Readers will find practical ways to reduce marital conflict, manage anger, build up one another`s self-esteem and listen and understand each other at deeper and more satisfying levels. This updated edition also includes all-new reflection questions at the end of each chapter for couples or groups. |
|
|
Key Float $5.95 Slippery Key Float Keeps your keys safely at surface if dropped in the water Quick clip for easy on/off when switching to different key rings |
|
|
Key Man Key Bag $10.99 [Idea] Let him hold all the key you have and avoid scratches in your pocket/bag; let the wonderful key man take all the wounds on your smart phone and other treasures!! [Features] Easy to find Protect things in the pocket Hanging-function available ?Specification? Color:Red/Brown Product Size: 9.2 × 8 × 3 cm Package Size: 10.2 × 6 × 4 cm Material: Silicone Made in Taiwan Size/Dimensions: Not Available Color/Finish: Brown |
|
|
Quality Management Your Key to Success $69.85 Dr Ralf Heron is not the typical, theoretical QM Guru, but rather a QM Entrepreneur. He started his career in Germany where he worked for over 15 Years as a Consultant and helped dozens of companies to reach their ISO 9000 Certifications. He then moved to Spain for 8 years followed by a journey to Dubai for 7 years, and is currently based in the United States. This diverse work experience of various regions across the globe and the exposure to widely different cultures has helped him to gain an indepth understanding of the issues involved in Quality Management implementation that made him a real practical QM Expert. Quality Management is the key to success, in this economy we are now. Only those Organizations that manage to have and keep satisfied customers will grow back into the market and Survive. History has shown and proven this many times over. The concepts of QM and ISO have been explained in an easy to understand manner by the author. Author: Heron, Dr Ralf Binding Type: Hardcover Number of Pages: 266 Publication Date: 2010/09/30 Language: English Dimensions: 6.00 x 9.02 x 0.75 inches |
|
|
Silver pendant Key to Your Heart (Peru) $117.95 Transforming precious Andean silver into art, Zilhi creates a mesmerizing pendant. She designs it like the key to a colonial palace with richly ornate detailing. "This should be a gift to your beloved, the key to your heart," she confides. .950 silver |
|
|
Silver pendant, 'Key to Your Heart' (Peru) $117.95 Transforming precious Andean silver into art, Zilhi creates a mesmerizing pendant. She designs it like the key to a colonial palace with richly ornate detailing. "This should be a gift to your beloved, the key to your heart," she confides. .950 silver |
|
|
Clear Gem Key to Your Heart Belly Ring $12.99 Clear Gem Key to Your Heart Belly Ring Keep the key to your fashion style close by with this heart lock belly ring. Surgical steel navel ring with key to your heart and heart lock dangle. Specifications: 14 Gauge (1.6mm), 7/16" (11mm), 316L Surgical Grade Stainless Steel, 5mm Ball Body Piercing Ring Body Jewelry |
|
|
Pink Gem Key to Your Heart Belly Ring $12.99 Pink Gem Key to Your Heart Belly Ring Keep the key to your fashion style close by with this heart lock belly ring. Surgical steel navel ring with key to your heart and heart lock dangle. Specifications: 14 Gauge (1.6mm), 7/16" (11mm), 316L Surgical Grade Stainless Steel, 5mm Ball Body Piercing Ring Body Jewelry |
|
|
Dupli-Key 2-Tag Key System $156.8 Organize and store two sets of keys. 20-gauge steel cabinet holds two of each key so one key always stays secure while the other key is in use or accidentally misplaced Two tags for each set of keys - red octagonal tag for original key and white oval tag for duplicate key When a key is loaned, a dated receipt hangs inside so you know where all your keys are at all times Cabinet can be wall mounted or used on a table or shelf Includes lockable cabinet, key loan register, cross reference index binder and key collection envelopes |


US $.79





















































































