5

I am working in PHP, I have to define variables in sequence to save in Mysql. Both field name and variable name must be same in my case.

Can I declare a variable like this

$1 OR $2 etc 

If not why not and if yes why yes?

I tried:

$id = 0;
$6  = $_REQUEST['6'];
$7  = $_REQUEST['7'];
$8  = $_REQUEST['8'];

$xary = array('6','7','8','9')

$oAppl->save_record("tablename", $id, "id");

which give me error.

Also can I create and use fields in Mysql with the same name?

hakre
  • 193,403
  • 52
  • 435
  • 836
Methew
  • 359
  • 4
  • 10
  • 28
  • Php could have variables starting with numbers, since every variable is prepended with $. But it is a convention. – Volkan Mar 15 '13 at 08:21
  • Do you want some similar functionality? Php is flexible. You can for example create $i0 to $i15 with a loop like that: for($x = 0; $x < 15; $x++)$GLOBALS['i'.$x]=null; – Volkan Mar 15 '13 at 08:27
  • possible duplicate of [Why can't variable names start with numbers?](http://stackoverflow.com/questions/342152/why-cant-variable-names-start-with-numbers) – Anant Dabhi Mar 18 '15 at 12:39

11 Answers11

18

This is how PHP was designed. You can't start a variable name with a number.

What you can do is use underscore:

$_6 = $_REQUEST['6'];

EDIT: since variables start with $ in PHP, is would be possible to have variables starting with numbers, but that would be a bit confusing to most people since there is no other language that allows variables starting with numbers (or at least I don't know any).

But let's imagine variables starting with numbers are allowed.

Can you imagine a coworker saying to you: 23 equals 74? That is a bit confusing. Hearing n23 equals 74 makes more sense. You know n23 is a variable without having to explicitly say that.

Robot Mess
  • 949
  • 1
  • 7
  • 31
  • PHP does allow variable names that consist of numbers only. Same identifiers in Mysql - It's just the question if that is useful. But to actually answer the concrete question: http://stackoverflow.com/a/19054047/367456 – hakre Sep 27 '13 at 15:04
  • Luckily programming languages are not spoken languages, @RobotMess :-P That way we have the benefit of knowing whether the co-worker is saying `23 == 74` or saying `23 = 74`. Of course I still get your point with that example. :-) – TylerH Mar 10 '14 at 20:11
7

Yes you can declare variables in PHP that start with a number:

${'1'} = 'hello';

This declares the variable with the variable name "1" in PHP.

To access it, you need to use the brace syntax again:

echo ${'1'};

This is necessary because in PHP code verbatim you can not write:

echo $1;

That would give a syntax error.


Also can I create and use fields in Mysql with the same name?

Yes you can, it works similarly as in PHP. In Mysql as well you need to quote the number-only identifier for the column, the quoting differs:

mysql> create table test (`0` INT);
mysql> describe test;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| 0     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+

Here the backticks are used (default Mysql configuration). Both the PHP manual and the Mysql manual explain the details of this, also there are many related questions to quoting identifiers both for PHP and Mysql on the Stackoverflow website.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    Decoding a json that have a variable name starting with a digit, the only way to access it is to use the syntax proposed by hakre. Having $json = '{"52WeekChange":"0,3"}'; You can access $decoded->{'52WeekChange'}; – Tama Mar 23 '17 at 17:53
  • I thought of this aswell. This is the closest you can get to it. But technically your variable starts with a curly brace ;-) – Ogier Schelvis Feb 23 '18 at 08:22
2

It does not make sense. But you can still use the dynamic names of variables.

<?php

$name = 1;

$ $name = 'name';
// $ 1 = 'name'; // the same, but syntax not allowed

var_dump($ $name); // value of $1
var_dump(${$name});
var_dump($$name);
Tegos
  • 405
  • 6
  • 14
1

Well think about this:

$2d = 42;
$a = 2d;

What is a? 2.0? or 42?

Hint, if you don't get it, d after a number means the number before it is a double literal

There being difficulty in unambiguosly determining whether a numeric character in the compilation unit represented a literal or an identifier.

Languages where space is insignificant (like ALGOL and the original FORTRAN if I remember correctly) could not accept numbers to begin identifiers for that reason.

This goes way back - before special notations to denote storage or numeric base.

For a more detailed discussion visit Why can't variable names start with numbers?

Community
  • 1
  • 1
Engineer
  • 5,911
  • 4
  • 31
  • 58
  • 2
    This is awfully wrong in this context. This was an answer to C syntax .. PHP variables start with $ , so your example is actually syntactically wrong. ($2d not 2d) – Naughty.Coder Jul 06 '15 at 09:34
  • PHP variables start with $. there is no reason not to allow numbers. except like [the bride that chops the end of the roast.](http://www.snopes.com/weddings/newlywed/secret.asp) – Dreaded semicolon Jan 07 '16 at 11:12
1

To augment @hakre's answer you could also lose the quotes for brevity

${1}

but alas, you can not combine that with a string value. I did some experiments and apparently PHP expects either a string or a number value. And you can do anything within the curly brackets that eventually returns a number or a string value or is implicitly cast to either.

<?php
function eight (){
   return 8;
}
${7+'fr'} = ${7*'fr'+1} = ${'hi'.((string)8).'hi'} = ${7.8910} = ${eight()} = ${(eight()==true)+4} = 'hi';

var_dump(get_defined_vars());

Outputs

array(8) { ["_GET"]=> array(0) { } 
["_POST"]=> array(0) { } 
["_COOKIE"]=> array(0) { } 
["_FILES"]=> array(0) { } 
["7.891"]=> string(2) "hi" 
["7"]=> string(2) "hi" 
["1"]=> string(2) "hi" 
["hi8hi"]=> string(2) "hi"
["8"]=> string(2) "hi" 
["5"]=> string(2) "hi" } 

Addtionally I found something interesting:

<?php
${false} = 'hi';
${true} = 'bye';

var_dump(get_defined_vars());

Outputs

array(6) { ["_GET"]=> array(0) { } 
["_POST"]=> array(0) { } 
["_COOKIE"]=> array(0) { }
[""]=> string(2) "hi" 
["1"]=> string(3) "bye" } 

Which means false evaluates to an empty string and not 0 and true to 1.

Ogier Schelvis
  • 602
  • 12
  • 22
0

As the php documentation says, you can't :

Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Concerning MySQL, the documentation says :

Identifiers may begin with a digit but unless quoted may not consist solely of digits.

Maen
  • 10,603
  • 3
  • 45
  • 71
0

You cannot define a variable starts with numerics in PHP. Take a look at the below link. It has the basics of defining variables.

PHP Variables - Basics

Edwin Alex
  • 5,118
  • 4
  • 28
  • 50
0

This is some kind of a legacy, starting with earlier-developed languages like C, Fortran etc. Also some shell script languages have special means for identifiers that start with a digit, namely input parameters. PHP standards simply decided to comply with this general rule.

Vesper
  • 18,599
  • 6
  • 39
  • 61
0

You can't name a variable starting with a number (or just a number for that matter). What you can do is use another character to start (for instance, and underscore, or a 3 lettercombo saying what type of variable it is:

$_1 = $_REQUEST['1'];

or

$str1 = $_REQUEST['1'];

What you can also do is use an array:

$retrievedValuesFromDB = array();
$retrievedValuesFromDB['1'] = $_REQUEST['1'];

This way you can loop through both at the same time:

$i=1;
while ($i<mysql_num_rows())
{
    $retrievedValuesFromDB[$i] = $_REQUEST[$i];
    $i++;
}
Borniet
  • 3,544
  • 4
  • 24
  • 33
0

First of all PHP was designed as a variable can't start with a number. Most of the languages are following the same naming rule. This is mainly for better readability and compiling performance optimisation. Backtracking is avoided in lexical analysis while compiling.

Suppose the variable like:

test = 12;
123test = 12;

The compiler will know test is a identifier right away when it meets letter 't'.

And in case of 123test, compiler won't be able to decide if it's a number or identifier until it hits 't' after 3, and it needs backtracking as a result.

Nishal K.R
  • 1,090
  • 11
  • 21
0

ALL THE ANSWERS THAT SAY THAT YOU CAN SUCCESSFULLY CREATE A NUM VARIABLE IN PHP ARE WRONG!

All the answers that say that {num} actually creates a variable with the name num are wrong.

If we create a variable that is a number using {1}, the $GLOBALS variable would not have it.

But the array returned by get_defined_vars() would probably have it (I don't get it sometimes)...

Now if I apply this logic in the other way, by using $GLOBALS to define a variable, the same thing would definitely happen.

Using this (dirty/unstable) logic is definitely not recommended (as directly described in the docs) and I am pretty sure you would never fall short of variable names while programming unless you are too much into syntactic brevity.

So please avoid using numbers at the start/as variable names altogether as you would have been expected to do in other languages

Henlo Wald
  • 37
  • 6