I have this problem that when I use array as such
Array
(
[11] => /2
[10] => /2
)
I'm unable to get the array name or the value when I use
for($i=0; $i < count($_SESSION['CHECKBOX']);$i++){
how can I get the name? and value? separate?
Given an array $_SESSION['CHECKBOX'], you can use:
foreach($_SESSION['CHECKBOX'] as $key=>$value) {
echo $key . '->' . $value . '<br />';
}
to get the key and values.
Utilize the foreach construct:
The foreach construct provides an easy way to iterate over arrays.
foreach works only on arrays and objects, and will issue an error when
you try to use it on a variable with a different data type or an
uninitialized variable. There are two syntaxes:
It will iterate your array and assign the key to the $key variable and the value to the $value array:
foreach($_SESSION['CHECKBOX'] as $key => $value){
echo "$key = $value";
}
Or concatenate the strings:
echo $key . '=' . $value;
Related
This question already has answers here:
Loop through associative array of associative arrays using foreach loop [closed]
(2 answers)
Closed 1 year ago.
I create an associative array in which there is an array, I want to print an associative array (key) and an array that is in it (value)
I have tried using a foreach but only managed to print the key but it shows an error for its value (Error: Array To String Conversion).
The second experiment, I tried using the foreach loop for the key and then used the loop for to print the value (Error: Undefined Offset).
<?PHP
$siswa = array(
"Kelas-X" => array("Joko", "Budi", "Duduk"),
"Kelas-XI" => array("Entong", "Timun", "Opang"),
"Kelas-XII" => array("Mamat", "Sadaw", "Koreng"),
);
foreach($siswa as $key => $value){
echo "Key : " . $key . "Value : " . $value;
}
?>
You cannot use echo on an array, you have to convert it to string before.
You can use json_encode for that.
Like this :
echo "Key : " . $key . "Value : " . json_encode($value);
Use two foreach loop
<?php
$siswa = array(
"Kelas-X" => array("Joko", "Budi", "Duduk"),
"Kelas-XI" => array("Entong", "Timun", "Opang"),
"Kelas-XII" => array("Mamat", "Sadaw", "Koreng"),
);
foreach($siswa as $key => $value){
foreach($value as $k => $v){
echo "Key : " . $key. "Value : " . $v;
}
}
?>
I want to echo the most common number from an array. I have one array and I want to compare the previous key with the current key of my array. How do I do that?
I have made two foreach loops:
$mostCommon = 0;
foreach ($_SESSION['array'] as $key => $value) {
foreach ($_SESSION['array'] as $key2 => $value2){
$key++;
}
if(current key is higher than previous key){
$mostCommon = $value;
}
}
This is how I wan't to do it.
You can save the previous key outside the loop.
Example:
$previousKey = null;
foreach ($array as $key => $value) {
if ($key > $previousKey){ //If current key is greater than last key
}
$previousKey = $key;
}
$highestKey will be set to the biggest key in that array.
The most common number can be found using array_count_values.
The output of array_count_values is an associative array with key being the value, and value being the number of times it's in the array.
Sort the array with asort to preserve the keys.
Flip the array to get the value that is the most common and echo the last item.
$arr = [1,2,2,3,3,3,3,1,2,5,3,7];
$counts = array_count_values($arr);
asort($counts);
$flipped = array_flip($counts);
echo "most common number: " . end($flipped) . " is in the array " . end($counts) . " times";
//most common number: 3 is in the array 5 times
https://3v4l.org/qSD4J
I am new in PHP.
My question is that when i use following script:
$arr1 = array('fname' => 'niraj','lname' => 'kaushal','city' => 'lucknow');
while(list($key, $value) = each($arr1)){
echo "$key has $value value <br>";
}
foreach($arr1 as $key => $value){
echo "$key:$value <br>";
}
it outputs
fname has niraj value
lname has kaushal value
city has lucknow value
fname:niraj
lname:kaushal
city:lucknow
but when i change order of foreach and while loop as follow
$arr1 = array('fname' => 'niraj','lname' => 'kaushal','city' => 'lucknow');
foreach($arr1 as $key => $value){
echo "$key:$value <br>";
}
while(list($key, $value) = each($arr1)){
echo "$key has $value value <br>";
}
it gives following output
fname:niraj
lname:kaushal
city:lucknow
Why second script doesn't display the output of while loop. What the reason behind it.
It is because each() only returns the current key/value and then advances the internal counter (where in the array you are currently). It does not reset it.
The first loop (foreach) sets the internal counter to the end of the array, so the second loop thinks it is already done and therefore does nothing.
You need to call reset() on the array before starting the loop using each():
reset($arr1);
while (list($key, $value) = each($arr1)){
echo "$key has $value value <br>";
}
I have listed an example below. What I need is for $key to return the actual index number (position) in the array during the loop, but instead it is returning Array. The same code works fine when given a single dimension array, but not in the example below.
GIVEN:
$screenshots would be similar to the following with only more entries.
Array
(
[0] => Array
(
[screenshot_id] => 871
[image_filename] => DSCF0124.JPG
)
)
PHP:
//build in clause & binding using selected array from above
$prefix = $in_clause = '';
$binding_clause = array();
foreach($screenshots as $key)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $key['screenshot_id'];
}
RESULT:
$inclause = :selected_Array
$binding_clause =
Array
(
[:selected_Array] => 871
)
EXPECTED:
$inclause = :selected_0
$binding_clause =
Array
(
[:selected_0] => 871
)
Just because you call it $key doesn't make it a key. You need the key and the value (inner array):
foreach($screenshots as $key => $value)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $value['screenshot_id'];
}
You need to tell it that you want the KEY and the VALUE.
like this:
foreach($screenshots as $key=>$screenShot)
That will get you the key and the value.
You just need to change your foreach to cast keys and values
foreach($screenshots as $key => $val)
Now the key is in your $key variable while you can access elements with $val array, for example $key['screenshot_id']
You can have a check to documentation examples here
Try:
foreach($screenshots as $key => $screenshot)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $screenshot['screenshot_id'];
}
Read more about PHP foreach: http://php.net/manual/en/control-structures.foreach.php
I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?
<?php
$pArray = Array();
if(!is_null($params['Name']))
$pArray["Name"] = $params['Name'];
if(!is_null($params['Age']))
$pArray["Age"] = $params['Age'];
if(!is_null($params['Salary']))
$pArray["Salary"] = $params['Salary'];
if(count($pArray) > 0)
{
//Loop through the array and get the key on by one ...
}
?>
Thanks for helping
PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:
foreach ($pArray as $key => $value)
{
print $key
}
//if you wanted to just pick the first key i would do this:
foreach ($pArray as $key => $value)
{
print $key;
break;
}
An alternative to this approach is to call reset() and then key():
reset($pArray);
$first_key = key($pArray);
It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.
Why not just do:
foreach($pArray as $k=>$v){
echo $k . ' - ' . $v . '<br>';
}
And you will be able to see the keys and their values at that point
array_keys function will return all the keys of an array.
To obtain the array keys:
$keys = array_keys($pArray);
To obtain the 1st key:
$key = $keys[0];
Reference : array_keys()