Find Value in Array Search Needle in Haystack Tutorial
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>