Array search dont know search - php

i have this array:
include("config.php");
$start = "2014-06-20 08:00:00";
$data = mysql_query ("select * from evenement WHERE start = '$start'");
$zaznam = mysql_fetch_array ($data);
while($zaznam = mysql_fetch_array ($data))
{
$arr2[] = $zaznam["resourceId"]; //store query values in second array
}
If i echo $arr2 i get this:
Array ( [0] => STK1 )
now i make condition for array_search:
if (array_search('STK1', $arr2)) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}
but i get this Arr2 not contains STK1
how it is possible? What im doing wrong?

That is totally correct behaviour for PHP.
The documention for the return value says:
Returns the key for needle if it is found in the array, FALSE otherwise.
In your case you are getting 0 which also evaluates to false in an if.
You have to check if the value is not false using the !== operator.
if (array_search('STK1', $arr2) !== false) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}

From the array_search documentation:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
array_search is returning 0 because it found a match at index 0 of the array. This is evaluating to false.
Instead try:
if (array_search('STK1', $arr2) !== false) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}

Related

How to determine if an array has any elements or not?

How do I find if an array has one or more elements?
I need to execute a block of code where the size of the array is greater than zero.
if ($result > 0) {
// Here is the code body which I want to execute
}
else {
// Here is some other code
}
You can use the count() or sizeof() PHP functions:
if (sizeof($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
Or you can use:
if (count($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
count — Count all elements in an array, or something in an object
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Counts all elements in an array, or something in an object.
Example:
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
In your case, it is like:
if (count($array) > 0)
{
// Execute some block of code here
}
If you want to only check if the array is not empty, you should use empty() - it is much faster than count(), and it is also more readable:
if (!empty($result)) {
// ...
} else {
// ...
}
You could avoid length retrieve and check using a simple foreach:
foreach($result as $key=>$value) {
echo $value;
}
#Sajid Mehmood in PHP we have count() to count the length of an array,
when count() returns 0 that means that array is empty
Let’s take an example for your understanding:
<?php
$arr1 = array(1); // With one value which will give 1 count
$arr2 = array(); // With no value which will give 0 count
// Now I want that the array which has greater than 0 count should print other wise not so
if (count($arr1)) {
print_r($arr1);
}
else {
echo "Sorry, array1 has 0 count";
}
if (count($arr2)) {
print_r($arr2);
}
else {
echo "Sorry, array2 has 0 count";
}
Pro Tip:
If you are sure that:
the variable exists (isset) AND
the variable type is an array (is_array) ...might be true of all is_iterables, but I haven't researched that extension of the question scope.
Then you don't need to call any functions. An array with one or more elements has a boolean value of true. An array with no elements has a boolean value of false.
Code: (Demo)
var_export((bool)[]);
echo "\n";
var_export((bool)['not empty']);
echo "\n";
var_export((bool)[0]);
echo "\n";
var_export((bool)[null]);
echo "\n";
var_export((bool)[false]);
echo "\n";
$noElements = [];
if ($noElements) {
echo 'not empty';
} else {
echo 'empty';
}
Output:
false
true
true
true
true
empty
For those who start with the array in PHP presented it this way:
more information here
//Array
$result = array(1,2,3,4);
//Count all the elements of an array or something of an object
if (count($result) > 0) {
print_r($result);
}
// Or
// Determines if a variable is empty
if (!empty($result)) {
print_r($result);
}
// Or
// sizeof - Alias of count ()
if (sizeof($result)) {
print_r($result);
}
<pre>
$ii = 1;
$arry_count = count($args);
foreach ( $args as $post)
{
if( $ii == $arry_count )
{
$last = 'blog_last_item';
}
echo $last;
$ii++;
}
</pre>

How to check if array is empty - true or false

I have a question, how do I put a condition for a function that returns true or false, if I am sure that the array is empty, but isset() passed it.
$arr = array();
if (isset($arr)) {
return true;
} else {
return false;
}
In this form returns bool(true) and var_dump shows array (0) {}.
If it's an array, you can just use if or just the logical expression. An empty array evaluates to FALSE, any other array to TRUE (Demo):
$arr = array();
echo "The array is ", $arr ? 'full' : 'empty', ".\n";
Sometimes it is suggested instead of just if'ing the array variable like:
if (!$array) {
// empty
}
to write out:
if (empty($array)) {
// empty
}
for readability reasons. Compare empty(php) language construct.
The PHP manually nicely lists what is false and not.
Use PHP's empty() function. It returns true if there are no elements in the array.
http://php.net/manual/en/function.empty.php
Use empty() to check for empty arrays.
if (empty($arr)) {
// it's empty
} else {
// it's not empty
}
You can also check to see how many elements are in the array via the count function:
$arr = array();
if (count($arr) == 0) {
echo "The array is empty!\n";
} else {
echo "The array is not empty! It has " . count($arr) . " elements!\n";
}
use the empty property as
if (!empty($arr)) {
//do what u want if its not empty
} else {
//do what if its empty
}

Is there a method to check if all array items are '0'?

I have an array
$data = array( 'a'=>'0', 'b'=>'0', 'c'=>'0', 'd'=>'0' );
I want to check if all array values are zero.
if( all array values are '0' ) {
echo "Got it";
} else {
echo "No";
}
Thanks
I suppose you could use array_filter() to get an array of all items that are non-zero ; and use empty() on that resulting array, to determine if it's empty or not.
For example, with your example array :
$data = array(
'a'=>'0',
'b'=>'0',
'c'=>'0',
'd'=>'0' );
Using the following portion of code :
$tmp = array_filter($data);
var_dump($tmp);
Would show you an empty array, containing no non-zero element :
array(0) {
}
And using something like this :
if (empty($tmp)) {
echo "All zeros!";
}
Would get you the following output :
All zeros!
On the other hand, with the following array :
$data = array(
'a'=>'0',
'b'=>'1',
'c'=>'0',
'd'=>'0' );
The $tmp array would contain :
array(1) {
["b"]=>
string(1) "1"
}
And, as such, would not be empty.
Note that not passing a callback as second parameter to array_filter() will work because (quoting) :
If no callback is supplied, all entries of input equal to FALSE (see
converting to boolean) will be removed.
How about:
// ditch the last argument to array_keys if you don't need strict equality
$allZeroes = count( $data ) == count( array_keys( $data, '0', true ) );
Use this:
$all_zero = true;
foreach($data as $value)
if($value != '0')
{
$all_zero = false;
break;
}
if($all_zero)
echo "Got it";
else
echo "No";
This is much faster (run time) than using array_filter as suggested in other answer.
you can loop the array and exit on the first non-zero value (loops until non-zero, so pretty fast, when a non-zero value is at the beginning of the array):
function allZeroes($arr) {
foreach($arr as $v) { if($v != 0) return false; }
return true;
}
or, use array_sum (loops complete array once):
function allZeroes($arr) {
return array_sum($arr) == 0;
}
#fireeyedboy had a very good point about summing: if negative values are involved, the result may very well be zero, even though the array consists of non-zero values
Another way:
if(array_fill(0,count($data),'0') === array_values($data)){
echo "All zeros";
}
Another quick solution might be:
if (intval(emplode('',$array))) {
// at least one non zero array item found
} else {
// all zeros
}
if (!array_filter($data)) {
// empty (all values are 0, NULL or FALSE)
}
else {
// not empty
}
I'm a bit late to the party, but how about this:
$testdata = array_flip($data);
if(count($testdata) == 1 and !empty($testdata[0])){
// must be all zeros
}
A similar trick uses array_unique().
You can use this function
function all_zeros($array){//true if all elements are zeros
$flag = true;
foreach($array as $a){
if($a != 0)
$flag = false;
}
return $flag;
}
You can use this one-liner: (Demo)
var_export(!(int)implode($array));
$array = [0, 0, 0, 0]; returns true
$array = [0, 0, 1, 0]; returns false
This is likely to perform very well because there is only one function call.
My solution uses no glue when imploding, then explicitly casts the generated string as an integer, then uses negation to evaluate 0 as true and non-zero as false. (Ordinarily, 0 evaluates as false and all other values evaluate to true.)
...but if I was doing this for work, I'd probably just use !array_filter($array)

php problem: strpos function not working

why is the following php code not working:
$string = "123";
$search = "123";
if(strpos($string,$search))
{
echo "found";
}else{
echo "not found";
}
as $search is in $string - shouldn't it be triggered as found?
This is mentioned in the Manual: strpos()
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
In your case the string is found at the index 0 and in php 0 == false
The solution is to just use the strict comparator
echo strpos($string,$search) === false
? "not found"
: "found";
Another one
echo is_int(strpos($string,$search))
? "found"
: "not found";
Or something ... lets say interesting :D Just for illustration. I don't recommend this one.
echo strpos('_' . $string,$search) // we just shift the string 1 to the right
? "found"
: "not found";
This is happening because the search string is being found at position 0.
Try
if(strpos($string,$search) !== FALSE)
instead of
if(strpos($string,$search))
strpos returns the first offset where $search was found - 0. 0 in turn evaluates to false. Therefore the if fails.
If $search was not found, strpos returns FALSE. First check the return value for !== FALSE, and then check the offset.
Thanks to everyone who pointed this out in the comments.
see: http://php.net/manual/en/function.strpos.php
From the manual:
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator
for testing the return value of this
function.
In your example, you should use
$string = "123";
$search = "123";
if ( false !== strpos( $string, $search ) ) {
echo "found";
} else {
echo "not found";
}
strpos returns the numeric position of the string you want to search for if it finds it. So in your case, you want to be doing this instead:
$search = "123";
$string = "123";
if (strpos($string,$search)===false) { echo "not found"; }
else { echo "found"; }
basically it returns a false if it doesn't find your string
You can use this:
<?php
$string = "123";
$find = "123";
$strpos = strpos($string, $find);
if($strpos || $strpos === (int)0) {
echo "Found it!";
} else {
echo "Not Found!";
}
?>
Well documented issue explained here. strpos is simply returning '0'

PHP & MySQL - How to check if an array is empty or not in a function

I was wondering how can I check if an array is empty or not in a function
Here is part of my code.
if (!mysqli_query($dbc, $sql)) {
trigger_error(mysqli_error($dbc));
return;
} else {
$t = array();
while($row = mysqli_fetch_array($result)) {
$t[] = $row[0];
}
}
if($tr > 0){
$ts = array_sum($t);
}
Use the empty() function:
http://php.net/manual/en/function.empty.php
Loose equivalency checking returns false on an empty array
if(array()) // returns false
http://php.net/manual/en/types.comparisons.php
Use count() to count the number of elements in the array.
An easy method would be to use the count function.
For example:
if(count($sourceArray) != 0) {
// Do exciting things here...
}
empty($t);
gives you true if $t is considered empty.
To check if array is empty:
if (sizeof($arr) == 0)
{
//Empty array
}
To check whether an element exists in an array or not:
if (in_array($element, $arr))
{
//Element found in the array
}

Categories