Count Array in php [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
if i use the count() in my php script.Either the value is zero also count variable returns 1.why?
Why php count values always returns 1?
Example 1:
$arr = array('php','sql');
echo count($arr);
output
2
Example 2:
$arr = array('');
echo count($arr);
output
1
even though i count the item in db also it return the same.
example
in my table their is no records
$query = mysql_query("select * from table_name");
echo count($query);
output
1

Because array is not empty
php > $array = array('');
php > echo count($array);
1
it already has a value a empty string => ""
php > print_r($array);
Array
(
[0] =>
)
count does not always return 1, that is pure phallacy, look:
php > echo count(array());
0

For arrays, count returns number of items in array.
Note, that array('') contains one item, not zero; the same is true for array(0), array(null), array(false), etc — each of them contains one item. Only array() contains zero items.
For most of other variable types, count almost returns 1. This is just a design decision — as calling count on "non-countable" values is useless, they'd decided to make it always return one.
mysql_query falls under this case. As mysql_query returns not array, but value of resource type. Thus $rsrc = mysql_query('...'); echo count($rsrc); will always return 1.
Also count behaves specially for null and objects, see here.

Related

how to merge data array of to array in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
how to merge data array of to array in php?
i have 2 arrays like:
$a=[1,2]; $b =[3,4];
and i want to merge data like:
$data = [[1,3]],[2,4]];
how to code in php like array_merge or something in php or laravel?
i have try using array_merge but not my expectation data like this:
$data = array_merge($a, $b);
but data always return
[1,2,3,4]
i have clue about this, can someone help this problem?
Since we concluded in the comments that you actually want a multidimensional array, we need to create new arrays so we can swap the values around between the original arrays.
Here's one possible solution (the comments explain the different parts)
$a = [1,2];
$b = [3,4];
// Initiate a new array
$newArray = [];
// Iterate through one of the arrays
foreach ($a as $index => $value) {
// On each iteration, take the values from both arrays for that specific array index
// and add them as a new sub array.
$newArray[] = [
$a[$index],
$b[$index]
];
}
$newArray will now contain a multidimensional array:
[[1,3],[2,4]]
Here's a demo: https://3v4l.org/okHhQ

Sorting the results of php for each loop into desending order (highest score top) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to display the results of a php for each loop in decending order, from reading a few similar questions here I have worked out I need to put the results of of the loop into an array then sort that, I have attempted to do that with the following code and getting a black page for the result..
$sql=mysqli_query($conn,"SELECT * FROM `live`");
/*every time it fetches the row, adds it to array...*/
while($liveuserscores[]=mysqli_fetch_array($sql, MYSQLI_ASSOC));
//Delete first line
array_pop($liveuserscores);
//echo '<hr><pre>'; print_r($liveuserscores); echo '</pre><hr>';
$sortedarr = [];
foreach ($liveuserscores as $user) {
$userpoints = $user['name'].": ".number_format($user['q1points']+$user['q2points']+$user['q3points']+$user['q4points']+$user['q5points']+$user['q6points']+$user['q7points']+$user['q8points']+$user['q9points']+$user['q10points']+$user['q11points']+$user['q12points']+$user['q13points']+$user['q14points']+$user['q15points']+$user['q16points']+$user['q17points']+$user['q18points']+$user['q19points']+$user['q20points']+$user['q21points']+$user['q22points']+$user['q23points']+$user['q24points']+$user['q25points']+$user['q26points']+$user['q27points']+$user['q28points']+$user['q29points']+$user['q30points']+$user['q31points']+$user['q32points']+$user['q33points']+$user['q34points']+$user['q35points']+$user['q36points']+$user['q37points']+$user['q38points']+$user['q39points']+$user['q40points'])."<br>";
$sortedarr = [] = $userpoints;
}
sort($sortedarr);
echo '<hr><pre>'; print_r($sortedarr); echo '</pre><hr>';
I also have
error_reporting(E_ALL);
ini_set('display_errors', '1');
in the code but getting no error messages.
a sample of print_r($liveuserscores); (with pre tags) is..
Array
(
[0] => Array
(
[ID] => 56
[name] => Glen
[datetime] => Tuesday 02nd Nov 21 21:26pm
[q1seen] => YES
[q1pickedans] => 2
[q1timetoans] => 2.375
[q1points] => 8
[q2seen] => YES
[q2pickedans] => 3
[q2timetoans] => 3.363
[q2points] => 7
)
)
I can get just the sum of users scores to display with this code...
$sql=mysqli_query($conn,"SELECT * FROM `live` ORDER BY name DESC");
/*every time it fetches the row, adds it to array...*/
while($liveuserscores[]=mysqli_fetch_array($sql, MYSQLI_ASSOC));
//Delete first line
array_pop($liveuserscores);
//echo '<hr><pre>'; print_r($liveuserscores); echo '</pre><hr>';
foreach ($liveuserscores as $user) {
echo $user['name'].": ".number_format($user['q1points']+$user['q2points']+$user['q3points']+$user['q4points']+$user['q5points']+$user['q6points']+$user['q7points']+$user['q8points']+$user['q9points']+$user['q10points']+$user['q11points']+$user['q12points']+$user['q13points']+$user['q14points']+$user['q15points']+$user['q16points']+$user['q17points']+$user['q18points']+$user['q19points']+$user['q20points']+$user['q21points']+$user['q22points']+$user['q23points']+$user['q24points']+$user['q25points']+$user['q26points']+$user['q27points']+$user['q28points']+$user['q29points']+$user['q30points']+$user['q31points']+$user['q32points']+$user['q33points']+$user['q34points']+$user['q35points']+$user['q36points']+$user['q37points']+$user['q38points']+$user['q39points']+$user['q40points'])."<br>";
}
But the order is not sorted by largest score at the top.
I see few problem with this code
first
array_pop($liveuserscores);
is removing the item you have just fetched from your array so you always working with a empty array, also array_pop remove the last element and not the first.
Also I-m pretty sure that this $sortedarr = [] = $userpoints; will reset $sortedarr to an empty array
Also sort function doesn't know how to sort an associative array, you have to define a sorting function using usort.
If I understood your question correctly you want to sort the results by the score.
And the score is the sum of few different column
You can change the query like this:
SELECT *,
q1points + q2points + ... + q40points AS score
FROM live
ORDER BY score DESC
So now you don't have to sort it manually
you can do
$sortedarr = mysqli_fetch_all($sql, MYSQLI_ASSOC);
echo '<hr><pre>'; print_r($sortedarr); echo '</pre><hr>';

different results array shortcode PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a question about the differents between the normal array code and the shortcode.
The output from the shortcode version has all the results.
But the normal code has only the last record of the data from the database.
Please is there somebody who can explain this?
Below the shortcode
<?php
while ($data = mysqli_fetch_assoc($result)) {
$output[$data['category']][] = $data['type'];
}
?>
Below the normal code
<?php
while ($data = mysqli_fetch_assoc($result)) {
//alleen laatste database result
$output = array($data['category'] => array($data['type']));
}
?>
When you assign
$output = <anything>;
you discard all the previous contents of $output, and replace it with the value of <anything>. So each time through the loop in the second version, you replace the variable with the data from the current row. When the loop is done, it just has the data from the last row.
You don't want to replace all of $output. It should be a multi-dimensional array, where the first dimension is associative with categories as keys, and the second dimension is an array of all type values in that category. Assigning to
$output[$data['category']][]
does two things:
$output[$data['category']] creates the category key in the first dimension if it doesn't already exist.
Assigning to [] pushes a new element onto the array in the second dimension.
It's equivalent to the following long code
while ($data = mysqli_fetch_assoc($result)) {
$cat = $data['category'];
if (!isset($output[$cat])) {
$output[$cat] = array();
}
array_push($output[$cat], $data['type']);
}

how to make both arrays equivalent with each other in php? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
It should be minimum number of action(moves);
Example : suppose we have 2 arrays
here both arrays as an example values.
$m = ['1234','3456'];
$n = ['2345','4567'];
step1 element of $m increment by 1(1+1,2,3,4) after that new value is = 2234
step2 element of $m increment by 1(2,2+1,3,4) after that new value is = 2334
step3 element of $m increment by 1(2,3,3+1,4) after that new value is = 2344
step4 element of $m increment by 1(2,3,4,4+1) after that new value is = 2335
total no of moves = 4
This is a way to doing it by code consider it as an example. you can use any way to make equal values.
Hope now you guys will get my point.
this will help to someone whoever is needed to break online php exams
$m = ['1234','2345'];
$n = ['2345','4567'];
$count = count($m);
$result = 0;
$response =0;
for($i=0;$i<$count; $i++){
if($m[$i]<$n[$i]){
$splitedm = str_split($m[$i],1);
$splitedn = str_split($n[$i],1);
$sCount = strlen($m[$i]);
for($j=0;$j<$sCount;$j++){
for($k=$splitedm[$j]; $k<$splitedn[$j]; $k++){
$result += $response+1;
}
}
}elseif($m[$i]>$n[$i]){
$splitedm = str_split($m[$i],1);
$splitedn = str_split($n[$i],1);
$sCount = strlen($m[$i]);
for($j=0;$j<$sCount;$j++){
for($k=$splitedm[$j]; $k<$splitedn[$j]; $k--){
$result += $response+1;
}
}
}
}
echo $result;
$m and $n having example values which i got in exam that's why i used the same.
step1 : first count no of element in array.
step2 : based on run for loop.
step3 : use if else condition to check which one is greater.
step4 : then split element value in single no (like- 1,2,3,4 for all).
step5 : now it is comparing one to one from $splitedm[$j] and $splitedn[$j]
step6 : consider every positive action as a move and storing in $result.
so that i can get minimum no of moves that can achieve the same value of $n elements.
hope you guys understand now.
This is my opinion to do that.
Happy Coding !!

PHP get value of array by position [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am pulling the latest 3 news articles from my database and I need to access them by the order they were pulled from, so first position in the array, second position and so on to display them in order in random sections of my web page. I came across accessing the array key but that is not working, where am I going wrong? Thanks in advance!
$value = array_slice($blog, 0, 1);
echo $value;
I think you are looking for a foreach loop or something like that:
$blog = array('foo', 'bar', 'cat');
foreach ($blog as $article) {
echo $article;
}
/**
* Gives you:
*
foo
bar
cat
*/
But if you want to do it with functions, you can use array_shift. This will remove the first element from an array and return that:
$article1 = array_shift($blog); // $blog is now `array('bar', 'cat')`
echo $article1; // >> foo
$article2 = array_shift($blog); // $blog is now `array('cat')`
echo $article2; // >> bar
$article3 = array_shift($blog); // $blog is now `array()`
echo $article2; // >> cat
Or if you want to keep the original $blog array, use array pointer functions like current, next, prev, reset and end:
reset($blog);
$article1 = current($blog); // >> foo
$article2 = next($blog); // >> bar
$article3 = next($blog); // >> cat
Use this :
$value = array_shift($blog);
To get second one
$value2 = array_shift($blog);
and third :
$value3 = array_shift($blog);
You have three different ways to accomplish this:
1. Call array_shift($blog) each time you want to get the next value.
$value = array_shift($blog);
Each time you do the array_shift it will return the next entry in the array.
Function array_pop is similar but returns the last entry in the array each time.
2. Simply access each entry of the array using the index
This gives the first entry in the array:
$value = $blog[0]
This gives the second entry in the array:
$value = $blog[1]
This gives the n'th value in the array:
$value = $blog[n-1];
3. Or finally you can simply loop through the array and echo out each entry (may not be suitable if you don't want to sequentially echo out the entries in the same place)
foreach ($blog as $blog_entry) {
echo $blog_entry;
}

Categories