#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2011
    Posts
    23
    Rep Power
    0

    PHP equivelant to Perl // operator?


    I'm looking for a PHP equivalent to the Perl // operator. My understanding (i.e. the context I've used it in before) is that this in Perl
    Code:
    $x = $y // $z;
    does this
    Code:
    if (defined $y) { $x = $y; } else { $x = $z; }
    Is there a PHP operator that does the same? There is this:
    PHP Code:
    $x = isset($y) ? $y $z
    but it tends to get ugly if $y is something like $ReallyLongVariableName
  2. #2
  3. Come play with me!
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,749
    Rep Power
    9397
    Strictly speaking no.

    If you can do without the isset()
    PHP Code:
    $x = ($y $y $z); 
    and have PHP 5.3+ you can use the shorthand form
    PHP Code:
    $x = ($y ?: $z); 
    but that is not the same as what you're asking: $y=0 or "" or false will also cascade to using $z, and if $y is to an array key that doesn't exist then you'll get a notice to that effect.

    However it sounds like your real problem is using long variable names. How about... don't?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2011
    Posts
    23
    Rep Power
    0
    Originally Posted by requinix
    Strictly speaking no.

    If you can do without the isset()
    PHP Code:
    $x = ($y $y $z); 
    and have PHP 5.3+ you can use the shorthand form
    PHP Code:
    $x = ($y ?: $z); 
    but that is not the same as what you're asking: $y=0 or "" or false will also cascade to using $z, and if $y is to an array key that doesn't exist then you'll get a notice to that effect.

    However it sounds like your real problem is using long variable names. How about... don't?
    I tired this and it didn't work. The error message is
    Code:
    PHP Notice:  Undefined variable: UNDEFINED in
    for the following line
    PHP Code:
    $n = ($UNDEFINED ?: 0); 
  6. #4
  7. Come play with me!
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,749
    Rep Power
    9397
    "...and if the variable doesn't exist then you'll get a warning for that too."

    So no.

    But why are you trying to use variables that don't exist? That doesn't sound good...

IMN logo majestic logo threadwatch logo seochat tools logo