I would like to find out if an array as a certain (number in this example) and print.
If value 0 in array $a contains 1.10 print out yes.
$a = array(1.10, 12.4, 1.13);
if (in_array([0] == '1.10')) {
echo "Yes";
}
No searching is required, just access the element using ordinary array indexing.
if ($a[0] == 1.10) {
echo "Yes";
}
You just need a minor adjustment in your in_array PHP function usage:
<?php
$a = array(1.10, 12.4, 1.13);
if (in_array(1.10, $a)) {
echo "Yes";
}
Yes
$a = array(1.10, 12.4, 1.13);
if (array_search('1.10', $a) === TRUE) {
echo "Yes";
}
This sounds like a job for array_search
which is used in the following manner:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
If it is in the data, $key is given the corresponding value of the element that contains the data you are searching for.
You need to learn proper syntax. Try:
if ( in_array('1.10', $a) ) {
echo "Yes";
}
//syntax
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Function Reference: http://php.net/manual/en/function.in-array.php
You can use aray_search it returns the corresponding key if successful.
$a = array(1.10, 12.4, 1.13);
if (array_search('1.10',$a) !== false) {
echo "Yes";
}
output:
Yes
you can speed up the function by turning on the strict mode:
it returns the corresponding key if successful.
$a = array(1.10, 12.4, 1.13);
if (array_search('1.10',$a,true) !== false) {
echo "Yes";
}
output:
Yes
array_search().in_arrayin their answers? He only wants to know if element 0 contains 1.10, not if it's anywhere in the array.