PHP can't print array elements without using print_r - php

I am using a db query that takes in a state and city then spits out 10 fields. Currently I can only see those fields by using print_r. I tried a suggestion on the php manual site a for loop to print the fields however I can't get it to work properly. Here is the code:
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row)."</p>";
$arrayLength = count($row);
for ($i = 0; $i < $arrayLength; $i++){
echo "arrayName at[" . $i . "] is: [" .$row[$i] . "]<br>\n";
}
}
}
And this is the result:
Array ( [id] => 1299 [zip_code] => 04011 [city] => Brunswick [county] => Cumberland [state_name] => Maine [state_prefix] => ME [area_code] => 207 [time_zone] => Eastern [lat] => 43.9056 [lon] => -69.9646 ) ....
arrayName at[0] is: []
arrayName at[1] is: []
arrayName at[2] is: []
arrayName at[3] is: []
arrayName at[4] is: []
arrayName at[5] is: []
arrayName at[6] is: []
arrayName at[7] is: []
arrayName at[8] is: []
arrayName at[9] is: []
Any ideas why I am not able to properly print the fields and their values? Also my code fails if the query returns more than one row as the current code doesn't really accommodate it.
I put $i in the body of the for loop to see if it was working properly. Ideally I would have the field name where $i is and the value to the right of it after the colon.

you are fetching with mysql_fetch_assoc so
change loop into
foreach($row as $key => $value){
echo "Array key : $key = $value <br/>";
}

Your array keys are 'id', 'zip_code' etc. There's nothing in the 0, 1 etc. indexes of the array.
foreach ($row as $key => $value) {
echo "arrayName at[" . $key . "] is: [" . $value . "]<br>\n";
// which is the same as:
echo "arrayName at[" . $key . "] is: [" . $row[$key] . "]<br>\n";
}

Yes, because that returns an associative array
That means that you have to access the elements like so:
$row["id"] for instance
What you want is this
foreach($row as $key => $value)
echo "arrayName at[" . $key . "] is: [" .$value . "]<br>\n";

use mysql_fetch_array() instead of mysql_fetch_assoc()
the mysql_fetch_assoc() will return an associative array and only accessable via $row['name'].
With mysql_fetch_array() you can fetch an associative array, a numeric array, or both.
take a look here: http://www.php.net/manual/en/function.mysql-fetch-array.php

Related

Calling index number location using PHP

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);
}

How to Loop Array Inside Associative Arrays [duplicate]

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;
}
}
?>

implode and show with key - php

I have an array with just a single element. The key and value looks like this:
Array ( [test] => 12342 )
Result i want is this inside an variable:
test = '12342'
I tried following:
$test = "'" . implode(" ", $metric) . "'";
print_r($test);
But this gives only gives me: '12342', i wanted the '=' after key and '' around the value (this is used for SQL later on). So the result should be test = '12342'. Does not look like implode would work here. I tried looking at http_query_builder but failed.
If this array is only ever going to contain one single item, then you don’t need to loop through the data, but you can use key and current instead:
$data = ['test' => 12342];
echo key($data) . " = '" . current($data) . "'";
key gets you the key of the “current” item, and current gets its value.
By just replying your question as it is using that unique example you would do it this way assuming there is only 1 value inside your array :
$yourArray = array('test' => '12342');
foreach($yourArray as $key => $value) {
$test = $key . " = '" . $value . "'";
}
print_r($test);
If there are multiple you would do this, as each key is unique :
$yourArray = array('test' => '12342', 'testing' => '24321');
$test = array();
foreach($yourArray as $key => $value) {
$test[$key] = $key . " = '" . $value . "'";
}
var_dump($test);

Ouputting array_count_values extracting key and values

This is probably so newbie. Basically im l
$count_versions = array();
while ($row = mysql_fetch_array($result))
{
$email_build = $row1['build_info'];
$count_versions[] = $email_build;
}
Now when I use print_r I get this
Array ( [2660] => 8 [2662] => 6 [2655] => 6 [2666] => 1 )
Which is perfect, now all I want to do is to output those values like
2660 - 8 votes
2662 - 6 votes
2655 - 6 votes
2666 - 1 votes
When I try this it seems to break up the values back into a full array which undoes my array_count_values but I am stumped
I realize this foreach loop makes no sense but its as close as I can get, any ideas how I can basically print it out like print_r does it so i can put it in a table later
$i=0;
foreach ($count_versions as $version => $nums)
{
$i++;
echo "Version: " . $nums . " - " . $count_versions . "<br />";
}
It looks so easy to do it with a foreach:
$count_versions = array ( "2660" => 8, "2662" => 6, "2655" => 6, "2666" => 1 );
foreach ($count_versions as $key => $value)
echo $key.' - '.$value.' votes<br>';
echo "Version: " . $version . " - " . $nums . " votes<br />";

PHP get name and value while using for

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;

Categories