Php переменная массив переменных

Php переменная массив переменных

It may be worth specifically noting, if variable names follow some kind of «template,» they can be referenced like this:

// Given these variables .
$nameTypes = array( «first» , «last» , «company» );
$name_first = «John» ;
$name_last = «Doe» ;
$name_company = «PHP.net» ;

// Then this loop is .
foreach( $nameTypes as $type )
print $ < "name_ $type " >. «\n» ;

// . equivalent to this print statement.
print » $name_first \n $name_last \n $name_company \n» ;
?>

This is apparent from the notes others have left, but is not explicitly stated.

In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).

This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter
an associative array :
array(‘index’=>’value’,’index’=>’value’);
index = reference to variable to be used within function
value = name of the variable to be used within function

$vars = [ ‘id’ => ‘user_id’ , ’email’ => ‘user_email’ ];

function validateVarsFunction ( $vars )

//$vars[‘id’]=34; // define allowed variables
$user_id = 21 ;
$user_email = ’email@mail.com’ ;

echo $vars [ ‘id’ ]; // prints name of variable: user_id
echo $< $vars [ 'id' ]>; // prints 21
echo ‘Email: ‘ .$< $vars [ 'email' ]>; // print email@mail.com

// we don’t have the name of the variables before declaring them inside the function
>
?>

The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It’s a kind of magic 🙂 This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking «$userName». You may easily omit:
$a = ‘username’;
echo $$a;

If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:

$price_for_monday = 10 ;
$price_for_tuesday = 20 ;
$price_for_wednesday = 30 ;

$price_for_today = $< 'price_for_' . $today >;
echo $price_for_today ; // will return 20
?>

PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

class Foo public function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$a = new $my_foo ();
$a -> hello (); //prints ‘Hello world!’
?>

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

class Foo public static function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$my_foo :: hello (); //prints ‘Hello world!’
?>

You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: —

foreach ( $array as $key => $value )
$ $key = $value ;
>

?>

This however would be reinventing the wheel when you can simply use:

extract ( $array , EXTR_OVERWRITE );
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: —

$array =array( «one» => «First Value» ,
«two» => «2nd Value» ,
«three» => «8»
);

extract ( $array , EXTR_PREFIX_ALL , «my_prefix_» );

?>

This would create variables: —
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: —
«First Value», «2nd Value» and «8» respectively

Another use for this feature in PHP is dynamic parsing..

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created. In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won’t need something this convolute. In this example, I needed to load an array with dynamically named objects — (yes, this has some basic Object Oriented programming, please bare with me..)

// this is only a skeletal example, of course.
$object_array = array();

// assume the $input array has tokens for parsing.
foreach ( $input_array as $key => $value ) <
// test to ensure the $value is what we need.
$obj = «obj» . $key ;
$ $obj = new Obj ( $value , $other_var );
Array_Push ( $object_array , $ $obj );
// etc..
>

?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven’t fully tested the implimentation of the objects. The scope of a variable-variable’s object attributes (get all that?) is a little tough to crack. Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

//.
foreach( $array as $key => $object )

echo $key . » — » . $object -> print_fcn (). »
\n» ;

?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.

Источник

Php переменная массив переменных

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23

but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :

$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>

Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.

Источник

Как преобразовать переменные в массив и массив в переменные?

У нас имеются некоторые переменные, которые мы бы хотели преобразовать в единый массив. Для этого нужно прописать имя массива и после знака равенства использовать данную функцию compact() , в скобках передав имена переменных, которые должны быть занесены в массив.

array compact ( mixed $varname1 [, mixed $. ] ) 

Создает массив, содержащий переменные и их значения.

Для каждого из переданного параметров, функция compact() ищет переменную с указанным именем в текущей таблице символов и добавляет их в выводимый массив так, что имя переменной становится ключом, а содержимое переменной становится значением этого ключа.

Список параметров

compact() принимает неограниченное количество параметров. Любой из параметров может быть либо строкой, содержащей название переменной, либо массивом названий переменных. Массив может содержать вложенные массивы названий переменных; функция compact() обрабатывает их рекурсивно.

Возвращаемые значения

Возвращает массив со всеми переменными, добавленными в него.

Пример

Массив в данном случае получится ассоциативным: в качестве ключей будут выступать имена переменных, а значениями, соответственно, будут значения переменных.

Преобразование массива в переменные. extract()

Для преобразования массива в переменные мы будем использовать функцию extract() .

int extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) 

Импортирует переменные из массива в текущую таблицу символов.

Каждый ключ проверяется на предмет корректного имени переменной. Также проверяются совпадения с существующими переменными в символьной таблице.

Список параметров

array — Ассоциативный массив. Эта функция рассматривает ключи массива в качестве имен переменных, а их значения — в качестве значений этих переменных. Для каждой пары ключ/значение будет создана переменная в текущей таблице символов, в соответствии с параметрами flags и prefix .
Вы должны использовать ассоциативный массив, использование числовых массивов не приведёт ни к каким результатам, если вы не используете EXTR_PREFIX_ALL или EXTR_PREFIX_INVALID.

flags — Параметр flags определяет способ трактования неправильных/числовых ключей и коллизий. Он может принимать следующие значения:
EXTR_OVERWRITE — Если переменная с таким именем существует, она будет перезаписана.
EXTR_SKIP — Если переменная с таким именем существует, ее текущее значение не будет перезаписано.
EXTR_PREFIX_SAME — Если переменная с таким именем существует, к её имени будет добавлен префикс, определённый параметром prefix.
EXTR_PREFIX_ALL — Добавить префикс prefix ко всем именам переменных.
EXTR_PREFIX_INVALID — Добавить префикс prefix только к некорректным/числовым именам переменных.
EXTR_IF_EXISTS — Перезаписать только переменные, уже имеющиеся в текущей таблице символов, в противном случае не делать ничего. Данная возможность полезна для определения списка приемлемых переменных и для извлечения только тех переменных, которые вы уже определили из массивов типа $_REQUEST, например.
EXTR_PREFIX_IF_EXISTS — Создать только префикс-версии переменных, если версия данной переменной без префикса уже существует в текущей символьной таблице.
EXTR_REFS — Извлечь переменные как ссылки. Это означает, что значения таких переменных будут всё ещё ссылаться на значения массива array. Вы можете использовать этот флаг отдельно или комбинировать его с другими значениями flags с помощью побитового ‘или’.
Если flags не указан, он трактуется как EXTR_OVERWRITE.

prefix — Обратите внимание, что prefix имеет значение, только если flags установлен в EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID или EXTR_PREFIX_IF_EXISTS. Если в результате добавления префикса, не будет получено допустимое имя для переменной, она не будет импортирована в текущую символьную таблицу.

Возвращаемые значения

Возвращает количество переменных, успешно импортированных в текущую таблицу символов.

Преобразование массива в переменные. $$

Для преобразование массива в переменные можно использовать конструкцию $$ — переменные переменных.

Пример

$expected=array('username','age','city','street'); foreach($expected as $key) < $= empty($_POST[$key]) ? null : $_POST[$key]; >

Фигурные скобки могут также использоваться, чтобы четко разграничить имя свойства.

Источник

Читайте также:  Python операторы цикла примеры
Оцените статью