-2

i'm a complete newb at php and i would like u to answer me about avoiding an error in some code like this for example:

<?php $some-randome-variable="random-variable" ?>

the result is an error, and that's cause of the minus sign. also, when i use minus in variables to give some statement, it's just cause errors.

i'm pretty sure there's some way to solve such kinda things, like with the squares and the

\

before it, u know...

thanks!

BIG THNX ALL, i'll stick with the underline then :)

  • You can't use minus signs in variable names because they are used in expressions PHP wouldn't know the difference between the variable name and you trying to do actual math. If you need some separator, use the underscore `_`. – Jonathan Kuhn Apr 22 '14 at 16:48
  • 6
    [The official docs](http://www.php.net/manual/en/language.variables.basics.php) describe what characters are legal in variable names. – Michael Berkowski Apr 22 '14 at 16:49
  • 2
    If you're a newbie, start by reading [the manual](http://www.php.net/manual/en/language.variables.php) – HamZa Apr 22 '14 at 16:49

3 Answers3

1

If you must have the hyphen in a variable name, you can do:

${'some-randome-variable'} = "random-variable";

However, it is definitely not advised to name your variables in that way. The above should only be used if you need to access a variable that you don't control, that has hyphens. For example from a third party library or web service response.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • 2
    I've replied exactly the same one minute later. Quoting myself: *When you learn a new language you'll be happier if you stick to the language conventions and not try to convert it into some other lang you learnt before ;-)* – Álvaro González Apr 22 '14 at 16:52
0

You can't use "-" for variables. You can only use numbers, letters and an underscore ("_")

0

You can't use a minus sign in a variable name in PHP

PHP thinks you are trying to subtract something from the variable

$variable-1

PHP tries to subtract 1 from $variable

http://www.php.net/manual/en/language.variables.basics.php

stick with underscore if it will help your readability

Douglas.Sesar
  • 4,214
  • 3
  • 29
  • 36