0
$var1=1; $var2=2; $var3='';
$array= array ( $var1 , $var2, $var3 );

echo count($array);
// Result (3)

I want the count result to be (2) and if possible without looping. I wonder if there's a way since I assume there are 3 keys counted. How do I eliminate the key with an empty value? This can simplify a lot of things to me.

5
  • 3
    count(array_filter($array)); Commented Dec 17, 2016 at 13:19
  • "and if possible without looping" Why, just why?! Commented Dec 17, 2016 at 13:20
  • nice, but is it possible to tell call_user_func_array() to see things that way without sending: Number of elements in type definition string doesn't match number ...? Commented Dec 17, 2016 at 13:27
  • @alexis That's not coming from call_user_func_array, that's coming frim mysqli_stmt_bind_param. The first argument is a string with the types of each placeholder, and the number of arguments has to match the size of that string. Commented Dec 17, 2016 at 13:51
  • That's why i was trying to unset the variable corresponding to a bind type (i) and to a (?) portion of the query string that i both dynamically remove. Still the corresponding variable even set to empty is counted despite its type and string portion no longer exist, and the error persisting. @Kris Roofe proposition was the keypoint to solve the problem by unsetting automatically the variable. Commented Dec 17, 2016 at 19:30

2 Answers 2

2

You can use array_filter to only keep the values that are non-empty in the array, like this:

array_filter($array);

So, to count only non-empty:

count(array_filter($array));

For the problem you mentioned in the comments. see if this helps:

suppose you have following array and a uery $sql:

$arr ="$name, $pass, $email, $contact, $company";
$result = $connection->prepare("$sql");
$newarr = array_merge( (array) $types, $arr);
call_user_func_array(array($result, 'bind_param'), $newarr);
Sign up to request clarification or add additional context in comments.

1 Comment

Any way to tell call_user_func_array() to see things that way while binding parameters and prevent error: Number of elements in type definition string doesn't match number of of bind variables...?
0

use

unset():

$var1=1; $var2=2; $var3='';
$array= array ( $var1 , $var2, $var3 );
unset($array[2]);

echo count($array);

2 Comments

I'm trying to exploit your way, looks like this could help
Your case helped the most to solve my problem. Thank you, but also thanks to all who tried to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.