Can I access an associative array by numerical index? - php

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>";

Related

how to create a variable for every element in an array

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.

PHP find max between variables

I'm trying to find out wich variable is bigger (those are all integers):
<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;
echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
I tried with max but it gives the value and not the $varName.
I want to get the name of the variable and if there are two that are equal I need both.
Thanks for the help.
As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...
$confronto = [
'ectoA' => $ectoA,
'ectoB' => $ectoB,
'endoA' => $endoA,
'endoB' => $endoB,
'mesoA' => $mesoA,
'mesoB' => $mesoB,
];
$result= array_keys($confronto,max($confronto));
$neurotipo = $result[0];
echo $neurotipo;
I want endoA and endoB to be identified...
You can define an array instead, or compact your variables into an array:
//$array = array('ectoA'=>3,'ectoB'=>5,'mesoA'=>0,'mesoB'=>4,'endoA'=>11,'endoB'=>11);
$array = compact('ectoA','ectoB','mesoA','mesoB','endoA','endoB');
$result = array_keys($array, max($array));
Then compute the max() of that array and use array_keys() to search for the max number and return the keys.
print_r($result);
Yields:
Array
(
[0] => endoA
[1] => endoB
)
I would definitely recommend using an array. Then you can do something like this:
$my_array = array(3, 5, 0, 4, 11, 11);
$maxIndex = 0;
for($i = 1; $i < count($my_array); $i++) {
if($my_array[$i] > $my_array[$maxIndex])
$maxIndex = $i;
}
Another option with array keys would be:
$my_array = array("ectoA" => 3, "ectoB" => 5, "mesoA" => 0, "mesoB" => 4, "endoA" => 11, "endoB" => 11);
$maxIndex = "ectoA";
while($c = current($my_array)) {
$key = key($my_array);
if($my_array[$key] > $my_array[$maxIndex])
$maxIndex = $key;
next($my_array);
}
Note: Code not tested, but should be the gist of what needs to be done
use the array like this
<?php
$value= array (
"ectoA" =>3,
"ectoB"=>5,
"mesoA"=>0,
"mesoB"=>4,
"endoA"=>11,
"endoB"=>11);
$result= array_keys($value,max($values))
print_r($result);
?>
As per the documentation, Since the two values are equal, the order they are provided determines the result $endoA is the biggest here.
But I am not sure your intention is to find the biggest value or which variable is the highest
Your code seems to be a working one.
But it would print for you the value of the maximum number, not the name of the variable.
To have the name of the variable at the end you should add some additional code like:
$max = (max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
if($max == $ectoA) echo "ectoA";
if($max == $ectoB) echo "ectoB";
// ... same goes for other variables
But working with an array would be the most proper solution.

Array initialisation with value

Hello guys i have coded something like this ..I just dont know wheather the code is right or not ..But i have a question
THe code is
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $value['name'];
}
I know that value of name can be acessed by $featured['name']
but now I just need to know wheather the key of array can be acessed with value like $value['name'].
Is it possbile like that ?..
Any help would be appreciated ..Thanks
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $key; // outputs: name
echo " - ";
echo $value; // outputs: 12
echo "<br />";
}
Yes, it supports that in the next iteration of the loop.
Output:
name - 12
yeah - 10
BTW, one more way of accessing the keys from array.
$featured = array('name' => 12,'yeah' => 10);
while (current($featured)) {
echo key($featured).'<br />';
next($featured);
}
Output:
name
yeah
You most probably want to do:
echo "{$key} => {$value}";
The foreach($featured as $key => $value) statement iterates the array and for each iteration $key and $value contain both the key and value for the tuple.
Take a look at this:
http://php.net/array_search
it searches for the value and returns it's key.
It's not like accessing $array['value'] but it's still userfull if you want to find the key.

How to store an array into a session variable in php

//Returns 10 question from questions table
$result = mysqli_query($con,"SELECT question FROM questions ORDER BY rand() LIMIT 10' ");
while($row = mysqli_fetch_row($result))
{
$que[]=$row[0];
}
Now I need to store this whole set of $que[] in a session variable. (i.e 10 questions)
Something like this
$_SESSION['question'] = $que[];
$my_array[] = $_SESSION['question'];
so that $my_array[0] returns first question, $my_array[1] returns second questions and like that.
(Thanx for the help in advance)
Assign
$_SESSION['question'] = $que;
print_r($_SESSION['question'][0]); will give you first question.
You are almost correct, you only need the [] when adding to the array.
$_SESSION['question'] = $que;
Make sure that you have a session going first, placing this at the top of your script will start a session if one doesn't already exist:
if( !isset( $_SESSION ) ) {
session_start();
}
To pull it back up:
$array = $_SESSION['question']; //Assigns session var to $array
print_r($array); //Prints array - Cannot use echo with arrays
Final Addition
To iterate over the array, you can typically use for, or foreach. For statements really only work well when your array keys are incremental (0, 1, 2, 3, etc) without any gaps.
for( $x = 0, $max = count($array); $x < $max; ++$x ) {
echo $array[$x];
}
foreach( $array as &$value ) {
echo $value;
}
Both have been written in mind for performance. Very important to know that when using a reference (&$value, notice the &) that if you edit the reference, the original value changes. When you do not use by reference, it creates a copy of the value. So for example:
//Sample Array
$array = array( '0' => 5, '1' => 10 );
//By Reference
foreach( $array as &$value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Now equals array( '0' => 7, '1' => 12 )
//Normal Method
foreach( $array as $value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Still equals array( '0' => 5, '1' => 10 )
References are faster, but not if you are planing on modifying the values while keeping the original array intact.
use
session_start();
$_SESSION['question'] = $que;
&que = array(an array of your 10m question s);
when your want to call it on another page to get a line up of your questions, use
while (list($key, $value) = each($_SESSION)) {
#Echo the questions using $key
echo "Here is a list of your questions";
echo "<br/>";
while (list($key2, $value2) = each($_SESSION)) {
#$value2 show's name for the indicated ID
#$key2 refers to the ID
echo "<br/>";
echo "Question: ".$value2." ";
echo "<br/>";
}
echo "<br/>";
}
OR you can also use
print_r;

Cleanest way of working out next variable name based on sequential order?

Hope my title explains it ok! Here's more detail:
I'm creating an array which stores keys & their values. Eg.
test1 = hello
test2 = world
test3 = foo
What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.
In the example below I want the next key to be 'test46', as it is the next highest value:
test6 = blah
test45 = boo
test23 = far
This sounds like you should be using an array with numerical indexes instead.
You could however use some code like this...
$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
$number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad.
Implementation of #alex answer without using a loop:
$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad
This data structure would be better stored as an array.
$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';
You then don't need to know the highest number to add a new item, just use the empty brackets syntax (shown above) to add an item to the end of the array.
You then have access to a wealth of array functions that PHP gives you to work with your data: http://php.net/manual/en/ref.array.php
When you want to get item 43 from the array, use:
echo $test[42];
Arrays are counted from 0 rather than 1, so item 43 will have an index of 42.
What are you using that for? If numbering the array is a must-have, just use a simple numerical indexed array instead, and simply prepend the key with "test" if you need it to show up as "test1":
<?php
$array = array(
6 => 'blah',
45 => 'boo',
23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "\n"; // this is 'new'
foreach( $array as $key => $value ) {
echo "test$key = $value<br />\n"; // test6 = blah
}

Categories