I tried this:-
function sum_array($arr_sum){
$string= "";
$length= count($arr_sum);
$sum= NULL;
if(is_string($arr_sum)){
echo "You cannot use string";
}else{
for($i=0; $i<$length; $i++){
$sum = $sum + $arr_sum[$i];
}
echo " The Sum is ". $sum;
}
}
$array_summation=["string",12.6,25.2,10,12];
sum_array($array_summation);
I want to know what should i do if i want only integer or float value inside an array, and if string come inside array it gives error that no string wanted or something like that
Use array_map to get the type of each value present in the array -
$type = array_map('gettype', $array_summation);
if (!empty($type) && in_array('string', $type) {
echo "You can't use string.";
}
Try this
function sum_array($arr_sum){
$sum = 0;
foreach($arr_sum as $value){
if(!is_numeric($value)){
echo 'Array Contain non numeric data';
exit;
}
$sum += $value;
}
echo 'The sum is '.$sum;
}
$array_summation=["string",12.6,25.2,10,12];
sum_array($array_summation);
PHP has a built-in array_sum function, which ignores non-numeric strings.
$arr = [1,2,'3','apple'];
var_dump(array_sum($arr)); // int(6)
Or if you really need them to produce an error you can use array_map:
function sum_array($arr) {
if (array_sum(array_map('is_numeric', $arr)) !== count($arr)) {
echo "You cannot use string";
return;
}
echo array_sum($arr);
}
sum_array([1,2,'3','apple']); // You cannot use string
sum_array([1,2,'3','5.2']); // 11.2
Or if you want to make sure that all values in the array are either floats or integers, and not numeric strings, you can do:
function is_non_string_number($n) {
return is_float($n) || is_int($n);
}
function sum_array($arr) {
if (array_sum(array_map('is_non_string_number', $arr)) !== count($arr)) {
echo "You cannot use string";
return;
}
echo array_sum($arr);
}
sum_array([1,2,'3','apple']); // You cannot use string
sum_array([1,2,'3','5.2']); // You cannot use string
sum_array([1,2,3]); // 6
Related
How do I find if an array has one or more elements?
I need to execute a block of code where the size of the array is greater than zero.
if ($result > 0) {
// Here is the code body which I want to execute
}
else {
// Here is some other code
}
You can use the count() or sizeof() PHP functions:
if (sizeof($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
Or you can use:
if (count($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
count — Count all elements in an array, or something in an object
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Counts all elements in an array, or something in an object.
Example:
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
In your case, it is like:
if (count($array) > 0)
{
// Execute some block of code here
}
If you want to only check if the array is not empty, you should use empty() - it is much faster than count(), and it is also more readable:
if (!empty($result)) {
// ...
} else {
// ...
}
You could avoid length retrieve and check using a simple foreach:
foreach($result as $key=>$value) {
echo $value;
}
#Sajid Mehmood in PHP we have count() to count the length of an array,
when count() returns 0 that means that array is empty
Let’s take an example for your understanding:
<?php
$arr1 = array(1); // With one value which will give 1 count
$arr2 = array(); // With no value which will give 0 count
// Now I want that the array which has greater than 0 count should print other wise not so
if (count($arr1)) {
print_r($arr1);
}
else {
echo "Sorry, array1 has 0 count";
}
if (count($arr2)) {
print_r($arr2);
}
else {
echo "Sorry, array2 has 0 count";
}
Pro Tip:
If you are sure that:
the variable exists (isset) AND
the variable type is an array (is_array) ...might be true of all is_iterables, but I haven't researched that extension of the question scope.
Then you don't need to call any functions. An array with one or more elements has a boolean value of true. An array with no elements has a boolean value of false.
Code: (Demo)
var_export((bool)[]);
echo "\n";
var_export((bool)['not empty']);
echo "\n";
var_export((bool)[0]);
echo "\n";
var_export((bool)[null]);
echo "\n";
var_export((bool)[false]);
echo "\n";
$noElements = [];
if ($noElements) {
echo 'not empty';
} else {
echo 'empty';
}
Output:
false
true
true
true
true
empty
For those who start with the array in PHP presented it this way:
more information here
//Array
$result = array(1,2,3,4);
//Count all the elements of an array or something of an object
if (count($result) > 0) {
print_r($result);
}
// Or
// Determines if a variable is empty
if (!empty($result)) {
print_r($result);
}
// Or
// sizeof - Alias of count ()
if (sizeof($result)) {
print_r($result);
}
<pre>
$ii = 1;
$arry_count = count($args);
foreach ( $args as $post)
{
if( $ii == $arry_count )
{
$last = 'blog_last_item';
}
echo $last;
$ii++;
}
</pre>
i have a function looks like this:
function foo($value)
{
echo "print: '".$value."' "
}
I want to pass an array as $value because i need to print a variable number of values. How can i pass them? This is what i have done and it doesn't work:
function foo($value)
{
$no = sizeof($value);
for($i=0;$i<$no;$i++)
{
//The if statement here prevents printing a comma at the end
if($i != ($no-1) )
echo $value[i].", ";
else echo $value[i] ;
}
}
Simple. Don't use a loop. All you're doing is spitting out your array as a comma-separated list, so:
function foo ($array_of_values) {
echo implode(',', $array_of_values);
}
First of all you forgot the $ before i in the loop while printing it.
function foo($value)
{
$no = sizeof($value);
for($i=0;$i<$no;$i++)
{
if($i != ($no-1) )
echo $value[$i].", ";
else echo $value[$i] ;
}
}
And secondly, the better way to do this is, use implode
function foo($values)
{
echo implode(',', $values);
}
better use foreach and check whether $value is set
or if you prefer your variant check $no
$no = sizeof($value);
if($no === 0) {
echo "parameter is empty";
return;
}
Recently I made a program to create 4 random numbers I want to put these numbers in an array but I did not echo the array's numbers :
my code is:
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[i] = rand_num_generator();
}
echo $number[2];
?>
Here i am not able to access array using their index values.
You missed the $ sign in front of the i inside $number[i] which must be used before a variable
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
//print_r($number);to see the whole array
You only echo once: at echo $number[i];, $i is 4, hence you only display the last random number.
You could loop on your array to echo each.
Put your echo into loop. And you have some mistakes. Use that:
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
To put something in an array I recommend to use array_push
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
array_push($numbers, rand_num_generator());
}
print_r($numbers); //Or use 'echo $numbers[0] . " " . $numbers[1]' etc etc
?>
How can I determine if one array is a subset of another (all elements in the first are present in the second)?
$s1 = "string1>string2>string3>string4>string5>string6>";
$arr1 = explode(">", $s1);
$s2 = "string1>string4>string5";
$arr2 = explode(">", $s2);
$isSubset = /* ??? */
if (array_intersect($array1, $array2) == $array1) {
// $array1 is a subset of $array2
}
Simple: use array subtraction.
On array subtraction, you will know whether or not one array is a subset of the other.
Example:
if (!array_diff($array1, $array2)) {
// $array1 is a subset of $array2
}
Reference: array_diff
You can use array_intersect also.
Try that
If you start from strings, you could check strstr($fullString,$subsetStr);. But that'll only work when all chars have the same order: 'abcd','cd' will work, but 'abcd','ad' won't.
But instead of writing your own, custom, function you should know that PHP has TONS of array functions, so its neigh on impossible that there isn't a std function that can do what you need it to do. In this case, I'd suggest array_diff:
$srcString = explode('>','string1>string2>string3>string4>string5');
$subset = explode('>','string3>string2>string5');
$isSubset = array_diff($subset,$srcString);
//if (empty($isSubset)) --> cf comments: somewhat safer branch:
if (!$isSubset)
{
echo 'Subset';
return true;
}
else
{
echo 'Nope, substrings: '.implode(', ',$isSubset).' Didn\'t match';
return false;
}
I would create an associated array of the larger array, then iterate through the smaller array, looking for a non collision, if you find one, return false.
function isSubset($arr1,$arr2){
$map = Array();
for ($i=0;$i<count($arr1);$i++){
$map[$arr[$i]]=true;
}
for ($i=0;$i<count($arr2);$i++){
if (!isset($map[$arr2[$i]])){
return false;
}
}
return true;
$s1 = "1>2>3>4>5>6>7";
$arr1 = explode(">",$s1);
$s2 = "1>2>3";
$arr2 = explode(">",$s2);
if(isSub($arr1,$arr2)){
echo 'true';
}else{
echo 'false';
}
function isSub($a1,$a2){
$num2 = count($a2);
$sub = $num2;
for($i = 0;$i < $num2 ;$i++){
if(in_array($a2[$i],$a1)){
$sub--;
}
}
return ($sub==0)? true:false;
}
Simple function which will return true if array is exact subset otherwise false. Solution is applicable for two dimensional array as well.
function is_array_subset($superArr, $subArr) {
foreach ($subArr as $key => $value) {
//check if keys not set in super array OR values are unequal in both array.
if (!isset($superArr[$key]) || $superArr[$key] != $value) {
return false;
}
}
return true;
}
I am trying to detect if one or more variables contain numbers. I have tried a few different methods, but I have not been entirely successful. Here is what I have tried.
<?php
$one = '1';
$two = '2';
$a1 = '3';
$a2 = '4';
$a3 = '5';
$string_detecting_array = array();
array_push($string_detecting_array, $one,$two,$a1,$a2,$a3);
foreach ($string_detecting_array as $key) {
if (is_numeric($key)) {
echo 'Yes all elements in array are type integer.';
}
else {
echo "Not all elements in array were type integer.";
}
}
?>
I haven't been successful using this method. Any ideas? Thankyou in advance!
First off, your loop logic is wrong: you should process all the items in the array before reaching a verdict. The shortest (although not most obvious) way to do this is with
$allNumbers = $array == array_filter($array, 'is_numeric');
This works because array_filter preserves keys and comparing arrays with == checks element counts, keys, and values (and the values here are primitives, so can be trivially compared).
A more mundane solution would be
$allNumbers = true;
foreach ($array as $item) {
if (!is_numeric_($item)) {
$allNumbers = false;
break;
}
}
// now $allNumbers is either true or false
Regarding the filter function: if you only want to allow the characters 0 to 9, you want to use ctype_digit, with the caveat that this will not allow a minus sign in front.
is_numeric will allow signs, but it will also allow floating point numbers and hexadecimals.
gettype will not work in this case because your array contains numeric strings, not numbers.
You can use gettype if you want to explicitly know if the variable is a number. Using is_numeric will not respect types.
If you are intending to use is_numeric but want to know if all elements are, then proceed as follows:
$all_numeric = true;
foreach ($string_detecting_array as $key) {
if (!(is_numeric($key))) {
$all_numeric = false;
break;
}
}
if ($all_numeric) {
echo 'Yes all elements in array are type integer.';
}
else {
echo "Not all elements in array were type integer.";
}
You can chain array_map with array_product to get a one-liner expression:
if (array_product(array_map('is_numeric', $string_detecting_array))) {
echo "all values are numeric\n";
} else {
echo "not all keys are numeric\n";
}
You can use this:
$set = array(1,2,'a','a1','1');
if(in_array(false, array_map(function($v){return is_numeric($v);}, $set)))
{
echo 'Not all elements in array were type integer.';
}
else
{
echo 'Yes all elements in array are type integer.';
}
You can create own batch testing function. It may be static function on your utility class!
/**
* #param array $array
* #return bool
*/
public static function is_all_numeric(array $array){
foreach($array as $item){
if(!is_numeric($item)) return false;
}
return true;
}
Use gettype()
http://php.net/manual/en/function.gettype.php
You have to set a flag and look at all the items.
$isNumeric = true;
foreach ($string_detecting_array as $key) {
if (!is_numeric($key)) {
$isNumeric = false;
}
}
if ($isNumeric) {
echo 'Yes all elements in array are type integer.';
}
else {
echo "Not all elements in array were type integer.";
}