When using an array in a foreach loop
$stdlist = rtrim(trim($_POST['stdlist'], '/'), '/');
$stdlist = explode('/' , $stdlist);
print_r($stdlist);
foreach($stdlist as $value)
{
echo "<br>";
echo $_POST[$value];
}
the array $stdlist is clearly working; when printed this returns:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 8 )
My problem is that when I use the foreach loop to extract out of the array one value at a time, the following gets printed to the page:
4
4
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35
I know this isn't functioning as intended as I am expecting the following:
1
6
7
8
Could somebody please explain why this is happening and how to fix this issue? Thanks :-)
You have to print the $value bacause $value have original array value not index.
And you are getting array in $stdlist from exploding this post variable $_POST['stdlist'].
foreach($stdlist as $value)
{
echo "<br>";
echo $value;
}
Now you will get your required result.
instead of using echo $_POST[$value]; just use echo $value when you use foreach loop for an array, the values on each nodes are automatically extracted.
foreach ($array as $index=>$value){
echo "index is $index and value associated with it is $value.";
}
Hope this helps.
foreach($stdlist as $value)
{
echo "<br>";
echo $value;
}
when you use foreach the $value is not the position in the array, if you want to use the position you need to do
for($pos=0; $pos<sizeof($stdlist); $pos++)
{
echo "<br>";
echo $stdlist[$pos];
}
When using the foreach() loop, I'd recommend assigning both the position and value to their own respective variables and then print them to the screen to see how the foreach loop has assigned the values.
foreach( $stdlist as $position => $value ) {
echo "The current position is $position, and the value of \$stdlist[$position] is
$value";
}
Related
I've got a bit of a problem, I have 2 inputs, one to type words, the other to find a keyword in the word array,
My code looks like this
if (isset($_POST['ord'])){
$name = $_POST['ord'];
$searchWord = $_POST['sök'];
$nameArray = (explode(" ", $name));
foreach ($nameArray as $key => $value) {
if ($value === $searchWord) {
echo substr_count($name, $value) ;
echo "<br>";
echo array_keys($value, $name);
break;
}
}
}
The problem I have is with this line
echo array_keys($value, $name);
I can only get it to call out the position of the index once before it stops, I want it to call out all the index positions, In this cause it would be 2 and 4
It might also have to do with the break; but then the problem remains that the break prevents the first line to repeat which is why I added it
This is what the output looks like (Can't post image yet)
Array ( [0] => hi [1] => Hey [2] => hi [3] => Hey )
The word Hey was found 2 times
Warning: array_keys() expects parameter 1 to be array, string given in C:\wamp64\www\labb-1a-php-sidor\sida3.php on line 39
You don't need a loop. Just call array_keys() correctly -- the first argument should be the array.
if (isset($_POST['ord'])){
$name = $_POST['ord'];
$searchWord = $_POST['sök'];
$nameArray = (explode(" ", $name));
$result = array_keys($nameArray, $searchWord);
echo "The word $searchWord was found " . count($result) . " times<br>";
var_dump($result);
}
i have an array
$array=(1,1,2,3,3,3,4);
i need to find each element how many times each element is exist in array .
So that i use
$occurences = array_count_values($array);
output is
Array
(
[1] => 2
[2] => 1
[3] => 3
[4] => 1
)
But i need to arrage the out put in following format
1 : 2
2 : 1
3 : 3
4 : 1
how can i do that ?
is there an other solution rater than using array_count_values
please help ;
Use foreach to iterate over every occurance and echo them out.
// If they are in wrong order, sort your array
ksort($occurences);
// Print output
if(count($occurences)>0){
foreach ($occurences as $key => $value) {
echo $key.' : '.$value.'<br />';
}
}
EDIT
To sort by no of occurances, use arsort.
arsort($occurences);
Of course, before printing it.
If 2:1 must come before 4:1 in your case, use:
asort($occurences);
arsort($occurences);
Just use this loop to have output like you need
foreach ($occurences as $k => $v) {
echo "$k : $v <br>";
}
You can use json_encode or array_keys and array_values
<?php
$array= array(1,1,2,3,3,3,4);
$occurences = array_count_values($array);
$array_keys = array_keys($occurences);
$array_values = array_values($occurences);
for($i=0; $i<count($array_keys); $i++) {
echo $array_keys[$i].':'.$array_values[$i].'\n';//add \n or \br tag
}
//you can echo json_encode
echo json_encode($occurences);
I'm working with an array that gives me all the info if print_r but it also says that it is an unidentified index.
Code:
foreach ($_SESSION['passo4'] as $key => $value) {
$x = $data_ref[0]['tipo_refeicao']; //gives me the error
echo $x; //echoes 1
print_r($data_ref);
if($key != 'preco'){
//Obter info do tipo de vestuário
$f_r = $dbh->prepare("SELECT tipo_refeicao, preco_acompanhante, preco_participante FROM refeicao WHERE id_extra = '$key'");
$f_r->execute();
$data_ref = $f_r->fetchAll();
echo "<tr><td>".
datasearch($data_tref, 'tipo_refeicao', $x, 'descricao')
."</td>";
echo "<td>". $value ."</td>";
echo "<td>". $data_ext[0]['preco'] * $value ."€</td></tr>";
}
}
Notice
Notice: Undefined offset: 0 in C:\xampp\htdocs\Rot.Aventura\eventos\passo5.php on line 96
Print_r($data_ref):
Array ( [0] => Array ( [id_refeicao] => 4 [id_evento] => 11 [tipo_refeicao] => 1 [preco_participante] => 5 [preco_acompanhante] => 6 [limite_pessoa] => 2 ) )
die($x): 1
Should i hide this notice with # or is there any way to solve this? (Sorry for the portuguese words)
Since you are in a foreach loop you don't have to use index 0. foreach auto increment the index, so on next index 0 is undefined
Please try without index or put $x out of loop
foreach ($_SESSION['passo4'] as $key => $value) {
...
$data_ref = $f_r->fetchAll();
$x = $data_ref['tipo_refeicao']; //gives me the error
or
foreach ($_SESSION['passo4'] as $key => $value) {
...
$x = $data_ref['tipo_refeicao']; //gives me the error
Give it a try
The problem was an error with my code:
$f_r = $dbh->prepare("SELECT tipo_refeicao, preco_acompanhante, preco_participante FROM refeicao WHERE id_extra = '$key'");
Where is id_extra it should be id_refeicao. Thank you for your time and help
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.
I want to print this array to all indexes upto 21, but in this code this is printing only to array length, what i should i do the print whole array in for loop?
<?php
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
$length=count($array);
for($i=0;$i<$length;$i++){
echo "$i=>".$array[$i];
echo "<br />";
}
?>
Your difficulty is the way you're defining your array:
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
Arrays in php are really hashmaps; when you call index 5 on the above array, it is undefined. No index item up to 20 will be defined, and these will Notice out:
PHP Notice: Undefined offset: 5
Because you're using array length as your iterating variable, and calling exactly that variable, you will never get positions 20 and 21 in your code.
This is what your array looks like to the computer:
0 => "hello"
1 => "world"
2 => "this"
3 => "is"
4 => "an"
5 => NULL
6 => NULL
7 => NULL
... //elided for succinctness
19 => NULL
20 => "array"
21 => "code"
When you call $array[7] it can't return anything. When you call $array[20] it will return "array".
What you really want is a foreach loop:
foreach($array as $key => $val) {
//key will be one of { 0..4, 20..21}
echo "$key is $value\n";
}
Resulting in:
$ php test.php
0 is hello
1 is world
2 is this
3 is is
4 is an
20 is array
21 is code
If you must use a for loop:
$key_array = array_keys($array);
for($i=0;$i<count($key_array);$i++){
$key = $key_array[$i];
echo "$key => ".$array[$key]."\n";
}
Note this is not a clean solution.
Solution with a for loop:
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
$max = max(array_flip($array)); // What if max array key is 10^5 ?
for($i=0;$i<=$max;$i++){
if(isset($array[$i])){
echo "$i=>".$array[$i]."<br>";
}
}
foreach($array as $key=>$value){
echo $key."=>".$value;
echo "<br />";
}
You want to start your loop with $i=0 as PHP uses zero indexing. also in your loop you want to cap your max value for interation at $i
<?php
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
$length=count($array);
for($i=0;$i<$length;$i++){
echo "$i=>".$array[$i];
echo "<br />";
}
?>