PHP - Add String to Array - php

I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:
$finalarray = $results_array + string;
A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray = $finalarray + $results_array["column"];
}
Edit:
Currently using this code (still not working):
$query = “SELECT * FROM table”;
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["name"];
}
echo $finalarray;
The problem is that it just says "Array"
Thanks,
Kevin

Answer to your edited question:
You cannot use just a single echo to print the entire array contents. Instead
Use
var_dump($finalarray);
or
print_r($finalarray);
to print the array contents..

Use the [] notation. + is for unioning two arrays.
$array = array('foo');
$array[] = 'bar'.
// $array == array('foo', 'bar')

You can use the function array_push or [] notation:
array_push($array, 'hi');
$array[] = 'hi';

Take a look at this
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["column"];
}
// Add X to the end of the array
$finalarray[] = "X";

Codaddict is correct. You are looking to output the last element that was added to the array.
echo end($final_array);
That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...
$finalarray[] = $results_array["name"];
The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...
echo $final_array[count($final_array) - 1];

echo implode($finalarray);
Or with a custom join "glue"
echo implode(', ', $finalarray);

Related

Divide randomly generated ids into equal groups

i'm using php and generating user's id like
$id = bin2hex(openssl_random_pseudo_bytes(16, $s));
And i would like to divide these ids into equals (or almost equals) groups. And in future i would like to know which group user belongs to.
Any ideas? What criteria can i choose for this?
I've found one variant of resolution. But maybe there is another, more pretty way...
$group = array_sum(str_split($id))%2;
OK this is a rough and ready answer; since the actual criteria you wish to sort on aren't given, I'm assuming the main goal is an even distribution of variables amongst your chosen container; I've used arrays here.
<?php
$id1 = 'abc';
$id2 = 'def';
$id3 = 'ghi';
$id4 = 'jk';
$id5 = 'lmn';
$id6 = 'opq';
$id7 = 'rst';
$id8 = 'uvx';
$id_array = array($id1, $id2, $id3, $id4, $id5, $id6, $id7, $id8);
$array1 = array();
$array2 = array();
$array3 = array();
$array4 = array();
$id_storage = array($array1, $array2, $array3, $array4);
$id_storage_size = sizeOf($id_storage);
foreach ($id_array as $indivId) {
$id_array_size = sizeOf($id_array);
$current_storage_array = $id_array_size % $id_storage_size;
$id_storage[$current_storage_array][] = $indivId;
array_shift($id_array);
}
//check them like so...
echo $id_storage[1][1];
?>
As for checking which array contains a given value:
<?php
$givenId = $id2;
foreach ($id_storage as $indiv_storage_array){
if (in_array($givenId, $indiv_storage_array)){
echo "Match found in $indiv_storage_array";
}
}
?>

PHP Array into array

I've had a look through searches but there are so many differently worded question that I'm not sure which I should be looking for. Nor can I think how to word this to the best of my ability, but here goes:
I would like to take a mysqli_fetch_assoc() result and create an array for each row.
Let's say the result had two rows:
[0][0] = Cheese
[0][1] = 1
[1][0] = Milk
[1][1] = 2
How can I drop those into a newly created array let's say called $items?
What I'm hoping to achieve is:
$items = array(
array("Cheese",1),
array("Milk", 2)
);
The only code I have so far is this:
if($row = mysqli_fetch_assoc($q)) {
for($i=0;$i<$total;$i++) {
$items[$i][] = $row[$i];
}
}
I have not tried this, but I have this very unsettling feeling that it definitely won't be working.
would this not do it?
if($row = mysqli_fetch_assoc($q)) {
foreach($row as $r) {
$items[] = $r;
}
}
$new_arr = array();
while ($row = mysql_fetch_assoc($q))
{
foreach($row as $value){
$new_arr[][$value[0]] = $value[1];
}
}
I think this is what you need
while ($row = mysql_fetch_assoc($q))
{
$arr = [];
foreach ($row as $value)
$arr[] = $value;
$items[] = $arr;
}
var_dump($items);
mysqli_result::fetch_all()
"Returns an array of associative or numeric arrays holding result rows"
I think you're thinking too hard. A two dimensional array is already an array containing arrays. In your case, the result of fetch_all is precisely an array containing 'an array for each row'
If you're not intending to store the whole result set then you can do:
$rows[] = Array();
while ($row = mysqli_fetch_row() && $someCondition) $rows[] = $row;
but really you'd be better off to put a LIMIT on the query if possible.

How to iterate through database results, compare each value to that in an array and return the matching id?

I am trying to build a function that will be given an array. and from this array, iterate through an entire table in the database trying to find a match. If it does find a match. I would like it to echo out the ID of that match from the database table.
If possible I would also like it to say if it found any close matches?
What's making this tricky for me is that it needs to match all values despite their order.
for example, if the function is given this array:
$array = array(1,2,3,4,5)`
and finds this array in the database:
$array = array(2,3,5,1,4)
it should consider this a match
Also, if it finds
array(1,2,3,4,5,6)
It should output this this as a match except for value 6.
Let me refrase your question, is this correct?
Based on an array of ID's, return all records whose ID's are in the array.
If so, use the IN operator:
SELECT *
FROM tableName
WHERE columnName IN (value1, value2, value3, etc.)
So first we need to transform the given array into a comma-seperated list:
$comma_seperated = implode(', ', $array);
Now we have a comma-seperated list we can use in our query:
$comma_seperated = implode(', ', $array);
$query = "SELECT *
FROM tableName
WHERE id IN (" . $comma_seperated . ")";
// execute query, don't use mysql_* functions, etc. ;)
You could use any of the options:
option 1:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM youtable WHERE id IN(".implode(",",$array).")";
option 2:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM yourtable";//Select ids
Now iterate through query results, say results are stored in $query_results,
$result=array();
foreach($query_results as $row){
if(in_array($row['id'],$array)){
$result[] = $row['id'];
}
}
You can use array difference to get the result just run the code and you will understand
Case 1
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array1, $array2);
print_r($result);
Case 2
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array2, $array1);
print_r($result);
And after that you can the count of $result and put it in your logic.
Case 1:
Maybe you can select the unique values from the database.
SELECT DISTINCT unique_values_that_need_for_compare_column FROM table
This SQL result will be the $databaseValues variable value.
Than iterate through the array that the function gets.
foreach ($functionArray as $value) {
if (in_array($value, $databaseValues)) {
// you have a match
echo $value;
}
}
Case 2:
Or you can make a query for every value:
foreach ($functionArray as $value) {
$query = "SELECT COUNT(*) as match FROM table WHERE unique_values_that_need_for_compare_column = " . intval($value);
// fetch the result into the $queryResult variable and than check
if ($queryResult['match']) {
// you have a match
echo $value;
}
}

PHP - Array in implode

I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.

PHP get the item in an array that has the most duplicates

I have an array of strings and I am looking for a way to find the most common string in the array.
$stuff = array('orange','banana', 'apples','orange');
I would want to see orange.
$c = array_count_values($stuff);
$val = array_search(max($c), $c);
Use array_count_values and get the key of the item:
<?php
$stuff = array('orange','banana', 'apples','orange', 'xxxxxxx');
$result = array_count_values($stuff);
asort($result);
end($result);
$answer = key($result);
echo $answer;
?>
Output:
orange

Categories