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;
}
Related
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
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
?>
Am trying to build a JSON array from a php array
This is my function in my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$last = end($data);
echo "[";
for($i = 0; $i < count($data); $i++) {
echo '{"user_id":"'.$data[$i][0]['user_id'].'",';
echo '"pheed_id":"'.$data[$i][0]['pheed_id'].'",';
echo '"pheed":"'.$data[$i][0]['pheed'].'",';
echo '"datetime":"'.$data[$i][0]['datetime'].'",';
if($i == count($data)) {
echo '"comments":"'.$data[$i][0]['comments'].'"}';
}else {
echo '"comments":"'.$data[$i][0]['comments'].'"},';
}
}
echo "]";
}
return false;
}
It returns a json array like this
[{"user_id":"9","pheed_id":"2","pheed":"This is my first real pheed, its got potential ","datetime":"1313188898","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"10","pheed":"Thank God for stackoverflow.com ","datetime":"1313358605","comments":"0"},]
But i cant seem to access it with jquery
I believe the problem rests with the trailing comma at the end of your array.
Rather than try to encode it yourself, use PHP's json_encode function. It's been tested and verified many, many times, so you don't have to reinvent the wheel.
Already voted up #derekerdmann, but thought I would add...
Your code will work, if you change:
if($i == count($data)) {
to
if($i == count($data) - 1) {
But, don't do that. If you are just putting everything from each member of the $data array into the json, then you should be able to just json_encode($data). If you are only pulling out certain parts, then build up a secondary array of your filtered data and json_encode that instead.
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$filtered_items = array();
foreach ($data as $member) {
$filtered_item = array();
$filtered_item['user_id'] = $member['user_id'];
$filtered_item['pheed_id'] = $member['pheed_id'];
...
...
$filtered_items[] = $filtered_item;
}
echo json_encode($filtered_items);
}
return false;
}
I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}
I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.
foreach($potentialMatches as $potentialKey)
{
$searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
$searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
{
$keyword = $searchKeyWordsRow['keyword'];
$pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
$pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
foreach($picValue['keywords'] as $key = > $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++;
echo $picValue['match'];
}
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
echo $picValue['match'];
}
I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.
Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']
In that second foreach you need to call it by reference:
foreach($pictureKeywordArray as $key => &$picValue)
{ //^-- `&` makes it by reference
foreach($picValue['keywords'] as $key => $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++; //now updates what you want it to update
echo $picValue['match'];
}
}
}
foreach works on a copy of the data. You must use a reference to modify the original:
foreach ($foo as $i => &$f)
{
$f++;
}
unset($f); // important to do this if you ever want to reuse that variable later