Effective way to get array index and value names - php

I have a 0 indexed array that I can't do much about, but inside this array there are values that I need to echo. example array is:
$x = array(0 => array('store'=> 107));
I would like to have 2 variables that both echo texts store and 107
I could do this, using
$var1 = array_keys($x[0]);
$var2 = array_values($x[0]);
echo $var1[0]; // store
echo $var2[0]; // 107
I would like to know if there is a more effective way of getting those values, or remving that first 0 index. as array_filter($x) or unset($x) obviously don't work as in other cases.

As an alternative, you could also use combinations of key() and reset() if you're curious.
$x = array(0 => array('store'=> 107));
$y = reset($x); // point to first element
$key = key($y); // get the current key, store
$val = reset($y); // get the value
echo $key; // store
echo $val; // 107

this should work for you.
$x = array(0 => array('store'=> 107));
foreach($x as $y){
foreach ($y as $key => $value){
echo $key;
echo $value;
}
}

Related

How to find the first, second, third etc numbers of an array

I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:
$numbers = range(1,4);
Then I shuffle with this:
shuffle($numbers);
Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:
foreach($numbers as $number){
$test = array("first"=>"$number");
echo $test['first'];
}
What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:
foreach($numbers as $number){
$test = array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth']," <br>";
}
This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.
If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)
You can use sizeof() it is return size of array size, and pass the key value manually. Like-
echo $numbers[0];
echo $numbers[1];
echo $numbers[2];
Here is a full code, try it
$numbers = range(1,4); //generate four numbers
shuffle($numbers); //shuffle them
$test = array(); //create array for the results
$words = array("1st", "2nd", "3rd", "4th","5th"); //create your array keys
$i=0;
foreach($numbers as $number){
$test[] = array($words[$i]=>$number); //add your array keys & values
$i++;
}
print_r($test); //show your results
If my understanding is correct you have an array and you want certain values from within it?
Then why not just use the array keys:
$array = array('peach','pear','apple','orange','banana');
echo $array[0]; // peach
echo $array[1]; // pear
echo $array[2]; // apple
Or you could loop through the array like so:
foreach ($array as $arrayKey => $arrayValue) {
// First value in the array is now below
echo $arrayKey; // 0
echo $arrayValue; // peach
}
You can also check if a value is in an array like so:
if (in_array('orange', $array)) {
echo 'yes';
}
Edit:
// Our array values
$array = array('peach','pear','apple','orange','banana');
// We won't shuffle for the example, we need expected results
#$array = shuffle($array);
// We want the first 3 values of the array
$keysRequired = array(0,1,2);
// This will hold our results
$storageArray = array();
// So for the first iteration of the loop $arrayKey is going to be 0
foreach ($array as $arrayKey => $arrayValue) {
// If the array key matches one of the values in the required array
if (in_array($arrayKey, $keysRequired)) {
// Store it within the storage array so we know what value it is
$storageArray[] = $arrayValue;
}
}
// Let's see what values have been stored
echo "<pre>";
print_r($storageArray);
echo "</pre>";
Would give you the following:
Array
(
[0] => 'peach'
[1] => 'pear'
[2] => 'apple'
)
Try this:
<?php
$numbers = range(1,4);
shuffle($numbers);
$test = array();
foreach($numbers as $k=>$v){
$test[$k] = $v;
}
echo "<pre>";
print_r($test);
?>
This will give you the output as:
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 1
)
After that you can do:
$myvar["first"] = $test[0];
$myvar["second"] = $test[1];
$myvar["third"] = $test[2];
$myvar["fourth"] = $test[3];
Every array has a key, value pair, if you have an array say:
$myarr = array("a", "b", "c");
then you can access the value "a" as $myarr[0], "b" as $myarr[1] and so on.
In the for loop I am looping through the array with their key and value, this will not only give you the key of the array but also the value associated with that key.
More on Array
Edit:
Improving what Luthando Loot answered:
<?php
$numbers = range(1,4);//generate four numbers
shuffle($numbers);//shuffle them
$test = array();//create array for the results
$words = array("first", "second", "third", "fourth"); //create your array keys
$i = 0;
foreach($numbers as $number){
$test[$words[$i]] = $number;//add your array keys & values
$i++;
}
echo "<pre>";
print_r($test); //show your results
?>
Output:
Array
(
[first] => 4
[second] => 3
[third] => 2
[fourth] => 1
)
use this way
$numbers[0];
$numbers[1];
$numbers[2];
$numbers[3];
Firstly make an array of keys as
$key = ['first','second','third','fourth'];
And then you can simply use array_combine as
$numbers = range(1,4);
shuffle($numbers);
$key = ['first','second','third','fourth'];
$result = array_combine($key,$numbers);
Demo

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;

get key and value of second last element of an array

i have an array of undefined size, for example :
<?php
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
?>
i don't want to disturb array's internal pointer , but want to get a COPY of second last value of array instead.
I don't know, why you use a map, when in fact you want an ordered list instead, but
$tmp = array_values($array);
echo $tmp[count($tmp) -2];
should do it. With php5.4 this should work either
echo array_values($array)[count($array)-2];
I'm not sure what size your array is planned for, so copying all values into a separate array might not be a good idea.
The following code slices out an array of length 1 just from the second last position and sets $key and $value.
$pair = array_slice($array, -2, 1, true);
$key = key($pair);
$value = current($pair);
PS: Should probably be put into a simple separated function?!
You can do it this way.
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
$x = count($array);
foreach($array as $row)
{
if($x == 2)
{ $secondLast = $row;}
$x--;
}
echo $secondLast;
Because you are using associative array.

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
}

Make array value variable (PHP)

Say I want to echo an array but I want to make the value in the array I echo variable, how would I do this?
Below is kind of an explanation of what I won't to do but it isn't the correct syntax.
$number = 0;
echo myArray[$number];
I'm not sure what you mean. What you have isn't working because you're missing a $ in myArray:
$myArray = array('hi','hiya','hello','gday');
$index = 2;
echo $myArray[$index]; // prints hello
$index = 0;
echo $myArray[$index]; // prints hi
Unlike other languages, all PHP variable types are preceded by a dollar sign.
Just to add more. Another type of array is associative array, where the element is determined using some identifier, usually string.
$arrayStates = array('NY' => 'New York', 'CA' => 'California');
To display the values, you can use:
echo $arrayStates['NY']; //prints New York
or, you can also use its numeric index
echo $arrayStates[1]; //prints California
To iterate all values of an array, use foreach or for.
foreach($arrayStates as $state) {
echo $state;
}
Remember, if foreach is used on non-array, it will produce warning. So you may want to do:
if(is_array($arrayStates)) {
foreach($arrayStates as $state) {
echo $state;
}
}
Hope that helps!
You are nearly there:
$number = 0;
$myArray = array('a', 'b')
echo $myArray[$number]; // outputs 'a'
$myArray = array("one","two","three","four");
$arrSize=sizeof($myArray);
for ($number = 0; $number < $arrSize; $number++) {
echo "$myArray[$number] ";
}
// Output: one two three four
$myArray = array('hi','hiya','hello','gday');
for($count=0;$count<count($myArray);$count++)
{
$SingleValue = $myArray[$count];
$AllTogether = $AllTogether.",".$SingleValue;
}

Categories