I want to give a little make up to my php code and I think its really annoying to check each time if the variable exists or not. Is there any cool way to make this code cleaner:
if (isset($array['key']) && $array['key']) {
}
What do you think?
another one
When you write foreach loop for object and you want to count the number of the current loop, how can you write this piece of ugly code to be prettier:
You either have to explicitly set a variable somewhere and test for a absence of a default value, or test that your variable is set otherwise if it is not set you will cause an error notice.
The old rule used to be “always declare your variables at the top of your file”.
$var = null;
//some stuff
if ( $var ) {
//do your thang
}
else
if( isset( $var )){
// do your thang
}
Up to you to choose which way suits you, but
if (isset($array['key']) && $array['key']) {
}
seems to contain a double check of the same thing essentially.
Actually if (isset($var)) is not the same as if ($var), the first will return true if the var exists, the second wil return true if the $var is not false or null… so they’re quite different
consider this
if (isset($var[‘test’]) && !$var[‘test’]) {
}
will give true if $var[‘test’] = false;
will give false if $var[‘test’] = true; or not defined
so basicaly I want to skip checking if var isset since it usually doesn’t make sense…
The second example when you used count, I wanted to know where in the loop you’re at (at which step), not the full number of elements in the object, beside that if you have an object - count function won’t work because its for arrays.
I did not read that properly, sorry. You can access the properties of a class like so:
class a {
public $var1 = 1;
public $var2 = 2;
function meth1(){}
function meth2(){}
}
$b = new a ;
foreach( $b as $c){
var_dump( $c );
}
// int 1
// int 2
echo count(get_object_vars($b));
// 2
but this will not work if you have private properties, though there is another, messier, way round it.
Whether that is what you meant by invoking a foreach loop on a single object, I am not sure.
To be honest, I find my variable checking when dealing with user input consists of some basic type-juggling or filtering - so do not concern myself with double set/exists tests such as you had in your first point.
// id MUST be an int otherwise the user is tampering data
if( (int)$_POST['id'] === 0 ){
// abort
}
// OR
if( (int)$_POST['id']) > 0 ){
// get on with stuff
}
Now if $_POST[‘id’] is optional, as in the case you have a single form which doubles as being the “Add new thing” or “Edit existing thing” depending on the existence of the id, then yes “is it set?” and “is it > 0?” is a double check I would do, and no I don’t know of any other way of making the check smaller/neater.