Create variables from array php

Converting an array to individual variables

Extract() is a very popular function that converts elements in an array into variables in their own right. Extract takes a minimum of one parameter, an array, and returns the number of elements extracted. This is best explained using code, so here goes:

After calling extract, the «England», «Scotland», and «Wales» keys become variables in their own right ( $England , $Scotland , and $Wales ), with their values set to «London», «Edinburgh», and «Cardiff» respectively. By default, extract() will overwrite any existing variables, meaning that $Wales ‘s original value of «Swansea» will be overwritten with «Cardiff».

This behaviour can be altered using the second parameter, and averted using the third parameter. Parameter two takes a special constant value that allows you to decide how values will be treated if there is an existing variable, and parameter three allows you to prefix each extract variable with a special string. Here are the possible values of the second parameter:

On collision, overwrite the existing variable

On collision, do not overwrite the existing variable

On collision, prefix the variable name with the prefix specified by parameter three

Prefix all variables with the prefix specified by parameter three, whether or not there is a collision

Only use the prefix specified by parameter three when variables names would otherwise be illegal (e.g. «$9»)

Only set variables if they already exist

Only create prefixed variables if non-prefixed version already exists

Extract variables as references

The last option, EXTR_REFS, can either be used on its own or in combination with others using the bitwise OR operator |.

Here are some examples based upon the $capitalcities array from the previous example:

On line one we pre-set $Wales to be a value so that you can clearly see how the second parameter works. On line two we call extract() using two parameters, with EXTR_SKIP as parameter two so that our $Wales will not be overwritten. However, as you will be able to see if you run the script, $England and $Scotland were set.

On line five we use EXTR_PREFIX_SAME, which will extract variables and use the third parameter as a prefix if it finds any collisions. As we set $Wales ourselves and our previous call to extract() created $England and $Scotland , all our variables will need to be prefixed. As you can see on line six, $Wales is still set to «Swansea», and on line seven we have our prefixed variable $country_England . Note that PHP places an underscore _ after your prefix to make the variable easy to read.

Finally we call extract() with EXTR_PREFIX_ALL, which will unconditionally create variables with prefixes, overwriting $country_England , etc. Note that EXTR_OVERWRITE is rarely if ever used, because it is the same as using extract() without second or third parameters.

Читайте также:  Java lang thread interrupt

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Источник

How to create variables using a php array?

This overhead can be avoided by using scalar variables instead of arrays. However, when an array only has a few records, the difference with scalar variables is nihil and performance should not really be an issue.

How to create variables using a php array?

I have a PHP array, something like below:

Array( [0] => Array ( [name] => month_year [value] => 201609 ) [1] => Array ( [name] => advance_amount [value] => 50% ) ) 

Using this array, I want to create 2 variables like this:

$month_year = '201609'; $advance_amount = '50%'; 

Can anybody tell me is this possible in php?

I tried it using two foreach but I don’t have any idea how to precced.

foreach ($_POST as $k => $data) < //echo "
", print_r($data)."

"; foreach ($data as $key => $value) < echo $key."
"; > >

Use variable variables. Your foreach loop should be like this:

foreach ($_POST as $k => $data) < $$data['name'] = $data['value']; >// display variables echo $month_year . "
"; echo $advance_amount;
$a = [['name' = 'month_year', 'value' => '201609'], ['name' => 'advance_amount', 'value' => '50%']]; foreach ($a as $line) < $= $line['value']; > php > echo $month_year; //201609 

Have a look at the Variables reference

Caution

Further dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7. The PHP 7.0 migration guide includes further details on the types of expressions that have changed, and how to place curly braces to avoid ambiguity.

using list it gives you the cleaner way to solve the issue: for example

$data = [ [ 'name' => 'month_year', 'value' => 201609 ], [ 'name' => 'advance_amount', 'value' => '50%' ] ]; list($month_year, $advance_amount) = array_map(function($value)< return $value['value']; >, $data); echo sprintf('Month of the year is %s with porcentage %s', $month_year, $advance_amount); 

This will have the result you are looking for with a clearer code.

Month of the year is 201609 with porcentage 50% 

first create loop and declare var.

 $data = array(array( 'name' => 'month_year', 'value' => 201609, ), array( 'name' => 'advance_amount', 'value' => '50%', ) ); foreach ($data as $key => $value) < $= $value['value']; > echo $month_year; echo '
'; echo $advance_amount;

Converting a PHP array to class variables, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

How to create a variable for every element in an array

$locations = [ 'name1', 'name2', 'name3', 'name4' ] 

Now I want to create variables say $location1, $location2.

which will hold value of name1, name2. respectively ( i.e., $location1 = ‘name1’, $location2 = ‘name2’. and so on

The array gets updated whenever admin adds new location so another variable must be created automatically to hold the name of new location from array.

Can it be done using php. Reason for this is I will need to access those variables and assign their values to javascript variable for displaying their name in map.

Any help would be appreciated.

if you want individual variables then you can use this program.

 $value) < $alocation['location' . $i] = $value; $i++; >extract($alocation); echo '
'; print_r($alocation); echo '

'; echo $location1 . '--' . $location2 . '--' . $location3 . '--' . $location4; ?>

$l = array('name1', 'name2', 'name3', 'name4'); $length = sizeof($l); for ($i = 0; $i < $length; $i++)< $= $l[$i]; > echo "$location1
$location2
$location3
$location4
";

You can initialize dynamic variables or use extract function.

Snippet for creating dynamic variables.

$locations = [ 'name1', 'name2', 'name3', 'name4' ]; foreach ($locations as $key => $val) < $<'location'.($key +1)>= $val; > echo $location3; 

Snippet for extract with prefix

$locations = [ 'name1', 'name2', 'name3', 'name4' ]; extract ($locations, EXTR_PREFIX_ALL, 'location'); echo $location_1; 

Note : prefix start from zero leading with underscore. Extract Docs

Sorry guys for your time spent on this question. I just needed to get an array from php to Javascript

Following code does exactly that

Now whenever the array in php script is updated, the array in javascript is automatically updated.

Thank you guys for one down vote as well.

You guys are awesome ( keep it up )

How to create variables using a php array?, I have a PHP array, something like below: Array( [0] => Array ( [name] => month_year [value] => 201609 ) [1] => Array ( [name] =&

PHP — Many variables or One array?

I have a question, what is more faster .

  1. I make many variables that contain all of my data, or
  2. I make one array in one variable that contain all of my data and access it

Test 1

$myvar1 = 'hello'; $myvar2 = 'hello'; $myvar3 = 'hello'; $myvar4 = 'hello'; $myvar4 = 'hello'; print_r(memory_get_usage()); 

Test 2

$myvar = array(); $myvar['var1'] = 'hello'; $myvar['var2'] = 'hello'; $myvar['var3'] = 'hello'; $myvar['var4'] = 'hello'; $myvar['var5'] = 'hello'; print_r(memory_get_usage()); 

Short: Accessing a variable is faster.

But still you might use arrays because of better code quality. To get better performance use caching. Anyway you should handle performance problems only when they occur!

Array Test
$n = 1000000; $startTime = microtime(true); for ($i = 0; $i $endTime = microtime(true); $elapsed = $endTime - $startTime; echo "Array: $elapsed seconds"; 
Variable Test
$startTime = microtime(true); for ($i = 0; $i $endTime = microtime(true); $elapsed = $endTime - $startTime; echo "Variable : $elapsed seconds"; 
Results

Also node that using arrays with string as index will be much slower (hashmap). Compare zend_hash_find vs zend_hash_index_find.

How big the array is does not really make a difference if I use $a = array_fill( 0, 1000, 1 ); and $x = $a2[999];

Memory

Not ask but also interesting is the memory usage. So I created an array with 10000 elements and 10000 variables.

$a = array(); for ($i = 0; $i print_r(memory_get_usage()); 

So arrays do use slightly less memory.

People here say that arrays are faster. But arrays are also variables. if you use an array — you still need to access it like any variable and additionally you need to access an item in array. So, it looks to me that array used like a storage for variables is not the best idea.

Additionally — arrays are used to store some array data. Like category category name pairs, for instance.

$catId1 = "Category 1"; $catId2 = "Category 2"; $catId3 = "Category 3"; 

Code like above would be. strange. You are loosing many features of an array, for instance, can’t go through all categories in for loop. So, for array data — array is what you need.

Once you have different kinds of data (talking about meaning of that data, not its type like integer or string) you should better use variables:

$requested_category = 1; $requested_category_name = "Some category"; $category_processing_result = "Ok"; 
$varsArray['requested_category'] = 1; $varsArray['requested_category_name'] = "Some category"; $varsArray['category_processing_result'] = "Ok"; 

With variables any IDE will help you to write those names, such code is easier to read and support. And that is more important, as for me.

Even if they are slower somehow, or take more memory — that is not a worst problem in terms of speed/memory usage for sure.

Many variables are faster than an array mainly because an array is an ordered map (http://php.net/manual/en/language.types.array.php) and therefore by definition for each and every value in the array, a reference key to the value in the array is also assigned. This costs extra memory and can have significant impact when speaking of hundreds of thousands of records in an array. The performance decreases as the number of records increases. This overhead can be avoided by using scalar variables instead of arrays.

Recently I was working on a profiler to measure memory and execution time using a tick callback. At first I used an array to log events and to keep track of all the measurements at each tick interval. After putting these values in separate scalar variables instead of in the array, I discovered that performance increased significantly (between 10 — 20% with 100000 — 1000000 records respectively).

However, when an array only has a few records, the difference with scalar variables is nihil and performance should not really be an issue. In such cases arrays might suit the situation better and be more effective, improve readability, maintenance and so on.

How to Convert object to array in PHP with example?, The following article provides an outline for PHP object to array. As we all know, object is known as a class instance which has memory allocated. In the case of an array, it is a data structure containing one or more values of a similar type in a single name. On the other hand, an associative array is not like a normal PHP …

Источник

Оцените статью