Count items inside an array - php

So i have an array full of random things (lets say fruits)
$fruit = array ("Banana", "Strawberry", "Apple",);
which is followed by a
echo implode (glue ' and ', $fruit);
which is supposed to list every single fruit that appears in the array
Now, how do I count the amount of items that appear wihtin in the list? As in how do i make the code show that it's 3 items

You can use the count() method of php.
Reference
For showing the amount you can use it like that:
echo "Amount: " . count($fruit);

You can use Count().
$fruit = array ("Banana", "Strawberry", "Apple",);
echo implode(' and ', $fruit) . " is " . count($fruit) . " fruits";
// Banana and Strawberry and Apple is 3 fruits
https://3v4l.org/19LqD

Related

How to count and display array values in php

I have one object array data coming below way.
$rooms= Single room,Single room,Single room ;
Here i want to display data below format
3 X Single room
For example rooms coming below format
Single room, Double room , Single room
then i need to out put is
2x single room
1x Double room
How to get like this ,Please tell me, i tried array_count_values and array_unique but not get result. Please any one know tell me
$str = rtrim(implode(",",explode("#", Single Room#DOuble Room#Single Room)));
$ss= str_replace(' ','',$str);
$ss1= str_replace(',',' ',$ss);
$rooms = explode(' ', $ss1);
//Count each occurence of values
$countedValues = array_count_values($rooms);
//Build strings from value and display them.
foreach( $countedValues as $roomType=>$count ){
echo $count . 'x ' . $roomType . '<br />';
}
I don't know how you're using array_count_values because you haven't posted your code, please post your code in future. Below is a working example that gives your desired output.
<?php
$rooms = "Single room,Single room,Single room,Double room";
$rooms = explode(',', $rooms); // array of rooms
//Count each occurence of values
$countedValues = array_count_values($rooms);
//Build strings from value and display them.
foreach( $countedValues as $roomType=>$count ){
echo $count . 'x ' . $roomType . '<br />';
}
?>
This gave me the output:
3x Single room
1x Double room
Please note that your question includes this:
$rooms= Single room,Single room,Single room ;
this is not a valid array format. You should use this instead:
$rooms = array("Single room","Single room","Single room");

loop in php function foreach

I try to get the result
danny love to eat orange and banana and grapes
Is it possible to get it through the function foreach
my Sample Code
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ';
//NOT THIS METHOD
// echo $var [0];
// echo ("and");
// echo $var [1];
// echo ("and");
// echo $var [2];
//Through this method
foreach ($var as $fruit) {
echo $fruit ;
echo ("and");
}
The result I get if i use foreach
danny love to eat orange and banana and grapes and
What's wrong ? :(
You're echoing 'and' one too many times. You don't want to echo 'and' if you're on the last element.
Try this instead.
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ' .implode('and',$var);
#bassxzero's answer is a great (In fact, I would recommend doing it that way over this way), but I wanted to show another way you could do this if you wanted to use a foreach loop still if you wanted to.
$var = array ("orange","banana","grapes");
$string = 'danny love to eat ';
//Through this method
foreach ($var as $fruit) {
$string .= $fruit. " and ";
}
$string = substr($string, 0, -5);
echo $string;
In my code, we are building a string that contains all the words that you want seperated by " and ". Then as soon as the loop is done, we use substr() to remove the very last " and " so that $string equals the string you were expecting.
Another solution could be
$var = array (" orange "," banana "," grapes ");
$str = 'danny love to eat ';
$total = count($var); // counts your aray
foreach ($var as $fruit) {
$total--; // decrements $total value
$str .= $total < 1 ? $fruit : $fruit.' and '; //if $total is reduced to 0 your loop is on the last repeat, so dont print 'and' anymore
}
echo $str;
Anyway implode way is the most elegant here.

PHP: Is it possible to get first two character from an array value?

Is it possible to get / select first two character from an array value?
for example:
Array
Array
(
[0] => 1_name
[1] => 0_sex
[2] => 2_age
}
and I need to get the first two character from each value in array's elements. So I can get this as a result if I echo them.
Result
First Element is 1_
Second Element is 0_
Third Element is 2_
Anyone know how to solve this? thanks
You could use array_map to get new array with only the first two characters of each item:
$input = ['1_name', '0_sex', '2_age'];
var_dump(array_map(function($v) { return substr($v, 0, 2); }, $input));
Use a foreach loop this way:
<?php
$a = ["1_name",
"0_sex",
"2_age"];
foreach ($a as $aa) {
echo substr($aa, 0, 2) . "\n";
}
Output:
1_
0_
2_
You can use the array_map() function as well to return an array.
array_map(function ($a) {
return substr($a, 0, 2);
}, $input);
Using indexes will work for you as well.
Source-Code
index.php
<?php
$array = [
'1_name',
'0_sex',
'2_age'
];
echo 'First element is ' . $array[0][0] . $array[0][1] . '<br>';
echo 'Second element is ' . $array[1][0] . $array[1][1] . '<br>';
echo 'Third element is ' . $array[2][0] . $array[2][1] . '<br>';
Result
First element is 1_
Second element is 0_
Third element is 2_

Php array in a foreach loop

I have been trying to create a Multidimensional array from an already existing array. The reason I am doing this is so I can separate the super array into a more categorized version so that later on I can run foreach on just those categories in another script.
This is a snippet of code // Please read comments :)
$and = array();
if($this-> input-> post('and')) // This is the super array and[] from a previous input field
{
if(preg_grep("/reason_/", $this-> input-> post('and'))) // Search for the reason_
{
foreach($this-> input-> post('and') as $value) // if reason_ is present
{
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
if(preg_grep("/status_/", $this-> input-> post('and'))) // Search for status
{
foreach($this-> input-> post('and') as $value) // If it is in the super array
{
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
This approach is not giving me expected outcome however, I am getting a big string like so :
array(2) { ["reason_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
["status_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
So to my knowledge (which is limited) when I try to do a foreach over the array
[reason_and]
I only get one loop since the array ["reason_and] only has one value (the 24 character string?). Is it possible to have the reason_and have a value for each of the numbers?
Is this even possible? I'm quite confused.
I've referred to this question for reference but I still do not get a outcome that I can work with. Thanks in advance.
This
$and['reason_and'] .= end(explode('_', $value)) . ' , ';
^^^^----
should be
$and['reason_and'][] = end(explode('_', $value)) . ' , ';
^^--
which turns it into an "array push" operation, not a string concatenation. Then 'reason_and' will be an array, and you foreach over it.
first of all preg_grep returns an array with matched values, so
$andArray = $this-> input-> post('and'); // This is the super array and[] from a previous input field
if($andArray) {
$reason = preg_grep("/reason_/", $andArray); // Search for the reason_
if($reason) { // if reason_ is present
foreach($reason as $value) {
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
$status = preg_grep("/status_/", $andArray); // Search for status
if($status) {
foreach($status as $value){ // If it is in the super array
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
Or if you need result as array, then remove ' , ' and replace dot with [];

Issue with summing arrays PHP

I'm trying to turn MySQL data into an array and then calculate the sum of that array.
$weight = ($product['av_id_1'])*$val; // get attribute values
$weightsub = explode(" ", $weight); // convert string to array
echo array_sum($weightsub);
I'm getting an output but its not what I expected, instead of a single integer its spaced integers like "30 40 50".
Where am I going wrong?
Thanks
$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo array_sum($weightsub)*$val;
First you need to extract all numbers using explode. Then apply array_sum to sum all numbers in the array, and multiply the sum by $val.
If this doesn't work as intended, you can easily do some basic debugging by using echo and print_r on each variable or result:
echo '$product[av_id_1] = <br>';
print_r($product['av_id_1']);
$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo '$weightsub = <br>';
print_r($weightsub);
echo "<br>\$val = $val<br>";
echo 'Sum = ' . array_sum($weightsub) . '<br>';
echo array_sum($weightsub)*$val;

Categories