how to create a variable for every element in an array - php

I have 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.
<?php
$locations = ['name1', 'name2', 'name3', 'name4'];
$alocation = array();
$i = 1;
foreach ($locations as $key => $value) {
$alocation['location' . $i] = $value;
$i++;
}
extract($alocation);
echo '<pre>'; print_r($alocation); echo '</pre>';
echo $location1 . '--' . $location2 . '--' . $location3 . '--' . $location4;
?>

try this
$l = array('name1', 'name2', 'name3', 'name4');
$length = sizeof($l);
for ($i = 0; $i < $length; $i++){
${"location".($i+1)} = $l[$i];
}
echo "$location1<br />$location2<br />$location3<br />$location4<br />";
Output
name1
name2
name3
name4

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;
Output:
name3
Live demo
Snippet for extract with prefix
$locations = [ 'name1', 'name2', 'name3', 'name4' ];
extract ($locations, EXTR_PREFIX_ALL, 'location');
echo $location_1;
Output:
name2
Live demo
Note: prefix start from zero leading with underscore.
Extract Docs

I just needed to get an array from php to javascript
Following code does exactly that
<?php $location = [....some values in this array...]; ?>
<script>var name = <?php echo json_encode( $location ) ?>;</script>
Now whenever the array in php script is updated, the array in javascript is automatically updated.

I don't know why you want to do this but I think the best way if you use JSON object so you can transform your array to JSON (json_encode, json_decode) very simplify and after that you can handle any way you want.

Related

How to select randomly from array exluding one value?

With the holidays slowly nearing, It's time to pick straws again. We always pick a piece of paper from a box containing everbody's name. However, this year I wanted to solve the issue of picking your own name from the box by using PHP.
I've got an array with names ex:
$names = [
'John',
'Jane',
'Joe',
'Matt',
'Steve',
'Anne',
'Karin'
];
For each of these names, I wanna pick 4 random names, so that at the end every person has 4 names for which they will have to buy a present.
The issue
Well, I'm stuck. I've thought of a million ways on how to do this but I just can't come up with anything.
What I've tried so far
Using a foreach
Using array_rand()
Shifting the array
The problem with these is that a person shouldn't be picking their own name and that everyone should be picked an even amount of times (4).
Update
Some great answers already posted. I'm not exactly sure though if this is fair for everyone. Everyone should at the end get 4 presents from 4 different persons.
I was thinking of adding each name to the $names array 4 times and then applying one of your answers. Am I on the right track with this?
Update 2
What I've tried now:
function select_rand($array, $exclude_array) {
$diff = array_diff($array, $exclude_array);
return $diff[array_rand($diff, 1)];
}
$workArray = [
'0' => $names,
'1' => $names,
'2' => $names,
'3' => $names,
];
foreach ($names as $k => $name) {
$i = 0;
$new[$name] = array();
while ($i < 4) {
$value = select_rand($workArray[$i], array_merge($new[$name], array($name)));
if (($key = array_search($value, $workArray[$i])) !== false) {
unset($workArray[$i][$key]);
}
$new[$name][] = $value;
$i++;
}
}
This works only in a few caes.
I would use shuffle, and array_slice for this job:
$names = [
'John',
'Jane',
'Joe',
'Matt',
'Steve',
'Anne',
'Karin'
];
foreach ($names as $name) {
// working array
$working = $names;
// remove current name from array,no one wants to buy presents for him/her self..
unset($working[$name]);
shuffle($working);
$people = array_slice($working, 0, 4);
echo $name . ' has to buy presents for:';
var_dump($people);
}
You can create custom function like as
$names = [
'John',
'Jane',
'Joe',
'Matt',
'Steve',
'Anne',
'Karin'
];
$my_name = "John";
$limit = 4;
function get_name($arr,$your_name,$limit){
$key = array_flip($arr)[$your_name];
unset($arr[$key]);
$rand_keys = array_rand($arr,$limit);
$result = array_intersect_key($arr, array_flip($rand_keys));
return implode(',',$result);
}
echo get_name($names,$my_name,$limit);
Demo
This can help -
function select_rand($array, $exclude_array) {
$diff= array_diff($array, $exclude_array);
return $diff[array_rand($diff, 1)];
}
$names = array(
'John',
'Jane',
'Joe',
'Matt',
'Steve',
'Anne',
'Karin'
);
foreach($names as $name)
{
$i = 0;
$new[$name] = array();
while($i < 4) {
$new[$name][] = select_rand($names, array_merge($new[$name], array($name)));
$i++;
}
}
This will generate a new array for each name (as key) in that array containing 4 unique names.
FIDDLE
Update
$new[$name][] = select_rand($names, array_merge($new[$name], array($name, 'Karin')));
I think if you want to have an even distribution of presents per person, you need to have more control over it. Anyhow, in this code I keep track of number of presents per person. I initialise it with zero: $presents = array_fill_keys($names, 0);. Then after each selection I updated this number $presents[$key]++;.
<?php
$names = array(
'John',
'Jane',
'Joe',
'Matt',
'Steve',
'Anne',
'Karin'
);
$presents_number = 4;
// initialization
$presents = array_fill_keys($names, 0);
$names_names = array();
foreach ($names as $i => $picker) {
$box = $names;
unset($box[$i]);
// filter out the people with maximum presents:
foreach ($presents as $key => $number) {
if (($presents[$key] > $presents_number-1) && in_array($key, $box)) {
$box = array_diff($box, array($key));
}
}
// shuffle the box and select 4 top
shuffle($box);
$selection = array_slice($box, 0, $presents_number);
foreach ($selection as $key) {
$presents[$key]++;
}
$names_names[$picker] = $selection;
}
echo "<pre>";
print_r($names_names);
echo "</pre>";
There can be more to be considered mathematically. Specially since loops can happen, this algorithm can go wrong. I haven't spend time on it. But as an example of 3 people and one present per person. (A, B, C)
correct answer:
A => {B}
B => {C}
C => {A}
wrong answer:
A => {B}
B => {A}
C => {}
Basically, the perfect algorithm should to avoid these wrong answers. Maybe later I fixed the problem as an update for this post.

Can I access an associative array by numerical index?

I would like to know if it is possible to get the x-value position (ie 2nd) in a variable variable array reference.
the code below works for the 1st array but not the 2nd.
// WORKS FINE //
$my1stArray= array( 'red', 'green', 'blue');
$var_1st = 'my1stArray';
// for each lopp of var var works fine
echo " - my1stArray Values - <br>";
foreach ($$var_1st as $k => $v){
echo $k." : ".$v." <br>";
}
// direct access also works
echo "my1stArray 3rd value: ".${$var_1st}[2]."<br>";
// Not so good! //
$my2ndArray = array(
'color' => '#ff0000',
'face' => 'helvetica',
'size' => '+5',
);
$var_2nd = 'my2ndArray';
// for each lopp of var_2nd works fine
echo "<br> - my2ndArray Values - <br>";
foreach ($$var_2nd as $k => $v){
echo $k." : ".$v." <br>";
}
/** try to access 2nd value in array with position **/
echo "my2ndArray 2rd value: ".${$var_2nd[1]}[0]."<br>";
echo "my2ndArray 2rd value: ".${$var_2nd}[1][0]."<br>";
Well, in the comments I said "no, you can't", but there is actually a way. Here is an example (without variable variables):
$my2ndArray = array(
'color' => '#ff0000',
'face' => 'helvetica',
'size' => '+5',
);
$keys = array_keys($my2ndArray);
echo "my2ndArray 2nd value: " . $my2ndArray[$keys[1]] . "<br>";
Doesn't look very nice, but should work. Not that if you ever sort the array, the key indexes will change.
Another way to do that would be using a counter and a loop as I mentioned in the comments. But that would be even uglier...
Your last example in your code is not working for the same reason that the following code does not work:
$a = array('akey'=>'a','bkey'=>'b');
echo $a[0];
The reason is the key is set to a string and must be accessed as such. To fix my example I would need to change it to:
$a = array('akey'=>'a','bkey'=>'b');
echo $a['akey'];
To fix your example you need to change your last echo so that it references the key as a string:
echo "my2ndArray 2rd value: ".${$var_2nd}['color']."<br>";

PHP Array. Change every row data in table to a string then pass to array

I am trying to use to a loop to pull all rows from a table, and change every row to a string then pass to an array. Here is the script I am currently working on.
PHP:
function toggleLayers(){
$toggleArray = array($toggle);
for($i=0;$i<$group_layer_row;$i++){
$toggle=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray($toggle);
}
}
Right now it only returns a string without passing to the array. Been looking and can't seem to find anywhere or anyone that can explain this to me in plain english.
Hope you can help. Thanks
I have no idea what vars are what in your example, but if you wanted to loop through an array and change its contents, here's how i'd do it:
$myArray = array( 'thing', 'thing2' );
// the ampersand will pass by reference, i.e.
// the _Actual_ element in the array
foreach( $myArray as &$thing ){
$thing .= " - wat?!";
}
print_r( $myArray );
will give you
[0] =>
'thing - wat?!'
[1] =>
'thing2 - wat?!'
I think you will gonna change your code to something like this:
$toggleArray = array();
for ($i = 0; $i < $group_layer_row; $i++) {
// push your string onto the array
$toggleArray[] = mb_convert_encoding(mssql_result($rs_group_layer, $i, 0), "UTF-8", "SJIS") . "_" . mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1), "UTF-8", "SJIS");
}
return $toggleArray;

PHP Count values of an array

Is there a way to count the values of a multidimensional array()?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
So for instance, I'd want to count the 3 values within the array "Test"... ('test1', 'test2', 'test3')?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
echo count($families["Test"]);
I think I've just come up with a rather different way of counting the elements of an (unlimited) MD array.
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function() { global $i; return ++$i; });
echo $i;
?>
Perhaps not the most economical way of doing the count, but it seems to work! You could, inside the anonymous function, only add the element to the counted total if it had a non empty value, for example, if you wanted to extend the functionality. An example of something similar could be seen here:
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function($value, $key) { global $i; if ($value == 'gh') ++$i; });
echo $i;
?>
The count method must get you there. Depending on what your actual problem is you maybe need to write some (recursive) loop to sum all items.
A static array:
echo 'Test has ' . count($families['test']) . ' family members';
If you don't know how long your array is going to be:
foreach($families as $familyName => $familyMembers)
{
echo $familyName . ' has got ' . count($familyMembers) . ' family members.';
}
function countArrayValues($ar, $count_arrays = false) {
$cnt = 0;
foreach ($ar as $key => $val) {
if (is_array($ar[$key])) {
if ($count_arrays)
$cnt++;
$cnt += countArrayValues($ar);
}
else
$cnt++;
}
return $cnt;
}
this is custom function written by me, just pass an array and you will get full count of values. This method wont count elements which are arrays if you pass second parameter as false, or you don't pass anything. Pass tru if you want to count them also.
$count = countArrayValues($your_array);

Position of Max value in Array PHP

Hey guys,
so I have two arrays
$names = array('jimmy', 'johnny', 'sarah');
$ages= array('16', '18', '12');
I am trying to find the biggest/maximum value in ages, get that elements position and use said position to get the corresponding name. How would I achieve this?
Is there a better way to achieve the corresponding name, perhaps bundling all in one?
Thanks
This should get the key for you:
$names = array('jimmy', 'johnny', 'sarah');
$ages= array('16', '18', '12');
$oldest = array_search(max($ages), $ages);
echo $names[$oldest];
You should note though, that if two persons would have the same age, the first of these two persons would be the one returned.
if you need to find all the oldest you should use array_keys() instead of array_search() like this:
$names = array('jimmy', 'johnny', 'sarah', 'kristine');
$ages = array('16', '18', '12', '18');
$oldestPersons = array_keys($ages, max($ages));
foreach($oldestPersons as $key) {
echo $names[$key].'<br />';
}
$oldest_key = 0;
$age_var = 0;
foreach ($ages as $key => $age) {
if ($age > $age_var) {
$age_var = $age;
$oldest_key = $key;
}
}
echo "Oldest person is: {$names[$oldest_key]} ($age_var)";
Just for fun, here's another solution:
$names = array('jimmy', 'johnny', 'sarah');
$ages= array('16', '18', '12');
$people = array_combine($ages, $names);
ksort($people);
echo 'Oldest person is: '.end($people);
See it in action.
Note: If many people have the same age, the one appearing last in the input arrays gets picked. This is a result of the behavior of array_combine.

Categories