tags:

views:

62

answers:

4

Several questions on "what is the shortest code for this?":

1) Without {}

if($match->name == "Marry") {
    $match = true;
}

2) Without {}

if($match->name == "Marry") {
    $match = true;
} else {
    $match = false;
}

3) How to ask if $match = true?


4) How to ask if array() has any value?


5) How to ask if $variable has numeric value (0-9)?


6) How to ask if $variable's first symbol isn't a letter or number?


7) How to ask if $match = false?


Thanks!

+2  A: 

1)

if($match->name == "Marry") {
    $match = true;
}

This is already short enough, you can't change it without hurting readibility (apart from maybe removing the braces).

2)

$match = ($match->name == "Marry");

Note you're using the same variable name.

3)

if ($match = true)

I suppose you want if ($match == true), which should be written just if ($match).

4)

(EDIT I read this as "has any (=some) value in particular", to check if the array is empty you can use empty)

See in_array.

5)

There are several ways, a possible one is

is_numeric($variable) && strlen("$variable") == 1

To allow starting 0s you could do

is_numeric($variable) && $variable >= 0 && $variable <= 9

6)

ctype_alnum($variable[0])
Artefacto
1 and 2 should be `Withous {}`.
hsz
@hsz I beg your pardon?
Artefacto
Technically you can remove the {}'s from an if block consisting of a single line. But I disagree with hsz. Missing them leads to headaches with strange code functionality.
Cags
+1  A: 

1)

$match = ($match->name == "Marry") ? true : $match;

2)

$match = ($match->name == "Marry");

3)

if ( $match === true ) {}

4)

$array = array();
if ( !empty( $array ) ) {}

5)

if ( is_numeric( $variable ) ) {}

6)

if ( ctype_alnum($variable[0]) ) ) {}
hsz
+1  A: 
1) OK
2) $match = ($match->name == 'Marry';
3) if ($match)
4) if (count($array))
5) preg_match('/^[+-]?\d+(\.\d+)?$/', $string)
6) preg_match('/^[^0-9a-zA-Z]/', $string)
M42
+1  A: 

A1. Can't really be shortened, accept in the case of part 2

A2. $match = ($match->name == "Marry");

A3. I suspect you mean...

if ($match) {
   echo "Value of $match evaluates as true";
}

A4. Not sure if you mean...

if (empty($array)) {
// or 
if (in_array($variable, $array)) {

A5.

if (is_numeric($variable)) {
   echo "it's numeric";
}

A6.

if (preg_match('#^[^a-z\d]#i', $variable) {
   echo "doesn't start with letter or number";
}
Cags