FULL STACK   ·   UI   ·   UX   ·   GRAPHICS   ·   DEVELOPER   ·   INSTRUCTOR

Adam Khoury

Donate funds to show love and support

Click the button below to donate funds securely online. You can use your PayPal account or a credit card.

Your donations help free up my time to produce more content and assist in covering server costs. It's also a great way to say thanks for the content!

Application Configuration

Adam will be adding options here soon.

Find Value in Array Search Needle in Haystack Tutorial

Published :
Author :
Adam Khoury
Learn to search for needles in haystacks using either PHP or JavaScript, which is a term used for looking in data arrays too see if a specific value exists. We also demonstrate how to optionally remove array elements where they match a value. Searching in an array for value(looking for a needle in a haystack): <?php $haystack = array('horse','goat','pig','chicken'); $needle = "pig"; $index = array_search($needle, $haystack); if(!array_search($needle, $haystack)){ echo $needle." NOT found in the PHP array"; } else { echo $needle." found in the PHP array"; } ?> <hr> <script> var haystack = ['horse','goat','pig','chicken']; var needle = "pig"; if(haystack.indexOf(needle) < 0){ document.write(needle+" NOT found in the JavaScript array"); } else { document.write(needle+" found in the JavaScript array"); } </script> Removing(delete) needle from haystack if needle is found: <?php $haystack = array('horse','goat','pig','chicken'); $needle = "pig"; $index = array_search($needle, $haystack); if($index){ unset($haystack[$index]); } echo serialize($haystack)." | ".count($haystack); ?> <hr> <script> var haystack = ['horse','goat','pig','chicken']; var needle = "pig"; if(haystack.indexOf(needle) > -1){ haystack.splice(haystack.indexOf(needle),1); } document.write(haystack+" | "+haystack.length); </script>