codeigniter get int value from string - codeigniter

I have a table with int values there. But, when I try to get the query result they all become strings in array.
Controller
$hitung['total'] = $this->nilais->ambil_total($id)->result();
var_dump result
array(3) { [0]=> object(stdClass)#21 (1) { ["bobot"]=> string(2) "20" } [1]=> object(stdClass)#22 (1) { ["bobot"]=> string(2) "30" } [2]=> object(stdClass)#23 (1) { ["bobot"]=> string(2) "30" } }
I want to add each integer (20 + 30 + 30).
How can I do that?

You can simply covert the string to int or u can use array_sum() to add

intval — Get the integer value of a variable
Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34
echo intval('042'); // 42
?>

first store value in variable from object like
$a=your_object_variable[0]->bobot;
$b=your_object_variable[1]->bobot;
$c=your_object_variable[2]->bobot;
$sum=(int)$a+(int)$b+(int)$c;
echo $sum

Related

Check if any date is older than 5 years

I am trying to figure out the best way to achieve something. I am looping through some data that involves a group of dates
foreach ($fields['dates'] as $key => $dates) {
$fields['dates'][$key]['datestring'] = Carbon::createFromFormat(
'dmY',
$dates['datestring']
);
var_dump($fields['dates'][$key]['datestring']);
}
The var_dump above produces something like the following
object(Carbon\Carbon)#330 (3) { ["date"]=> string(26) "2019-08-08 12:41:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } object(Carbon\Carbon)#328 (3) { ["date"]=> string(26) "1987-08-08 12:41:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
So above this, I have created a variable to identify whether at least one of the dates is more than 5 years ago. I have also created a date object for today.
$moreThanFiveYears = false;
$now = Carbon::now();
Now what I am trying to figure out is how I perform the actual check? When I try the above, it complains because $now is not the same format as my other dates. I have tried adding a format to it, but it produces only something like 20190219 and not the additional data the original dates produce.
So how can I loop all my dates to ensure at least one is greater than 5 years?
Thanks
get five years ago by subYears() and compare them by greaterThan().
$fiveYearsAgo = Carbon::now()->subYears(5);
foreach ($fields['dates'] as $key => $dates) {
$fields['dates'][$key]['datestring'] = Carbon::createFromFormat(
'dmY',
$dates['datestring']
);
if ($fields['dates'][$key]['datestring']->greaterThan($fiveYearsAgo)) {
$moreThanFiveYears = false;
}
}
Try out this.
<?
$check_date = '2019-12-18 18:20:40';
if(strtotime($check_date) < strtotime('-5 year')){
echo "YES";
}else{
echo "NO";
}
?>
Since you are using Carbon, you can make use of the difference methods, which allow you to easily calculate the difference between two dates, in any unit:
diffInSeconds()
diffInMinutes()
diffInHours()
diffInDays()
diffInYears()
# existing date
$old = Carbon::parse("2010-01-20 12:00:00");
# current date
$now = Carbon::now();
# find the difference
$diff = $old->diffInYears($now);
# test your difference
if($diff > 5) {
echo "date is older than 5 years";
}
Note: since you are calculating difference, the order of the comparables does not matter - the answer would be the same in both cases:
$diff = $old->diffInYears($now);
$diff = $new->diffInYears($old);

foreach not working in Drupal 7

I want to execute following code to trace array value in drupal module. But it's not working. In PHP my code works fine but shows notice in Drupal. How to write foreach in Drupal module?
foreach($submission as $s) {
foreach ($s as $a) {
echo $sid = $a[1]->sid;
}
}
Notice: Undefined offset: 1 in webform_submission_publish() (line 149
of
Because you have an undefined offset, the code will break.
You can prevent this kind of mistake by checking if the array is set.
foreach ($submission as $s) {
foreach ($s as $a) {
if (isset($a[1])) {
echo $sid = $a[1]->sid;
}
}
}
Documentation:
http://php.net/manual/en/function.isset.php
Surely, you can check for the index 1 before using it, but it's a bit odd to access the value indexed by 1, which is likely to be the second element in the array. You can get the first element using the PHP reset() function. So, the echo line would read
echo $sid = reset($a)->sid;

How I can get 0 index value in codeigniter?

Array ( [0] => 18 [1] => 1 )
how i can get only 0 index value?. I am using this code in codeigniter. Can any one help?. Is this possible with for each loop so it access all indexes but show only zero index?
foreach($m as $m)
{
echo $m->['0'];
}
If you want only first index then you don't need to foreach loop
Just write:
echo $m[0];
And if you want all index of array then:
foreach ($m as $key => $value) {
echo $key;
}
Try this:
print_r($m[0]);
or
foreach($m as $m)
{
echo $m['0'];
}
Following is the code to get value of index 0
//$array variable declared containing multiple values
$array=array('0' =>"first value",'1' =>"second value",'2' =>"third value" );
echo "<pre>";
print_r($array); // helps in printing the value key and value
//iterating through each values in the array
foreach ($array as $key => $value) {
if($key==0) //checks if key is 0
{
echo $value; //prints the value in key 0
}
}

Check if a value is present in a comma separated varchar string

I have a record "id_zone" in database that store cites id like this $abilitato->id_zone = '1, 2, 3, 9, 50'
From laravel i need to check if a value passed from url is present in this field. The following work only if i have a single value
$abilitato = \App\Models\Servizi::where('id', $servizio)->('id_zone', $verifica->id_citta)->first();
if(!empty($abilitato) && empty($verifica->multicap)) {
$json = ['CAP' => '1' , 'DEB' => $cap ];
}else{
$json = ['CAP' => '0' , 'DEB' => $cap];
}
i need to check if
If you want to know if a value is in your array you can use this functión to know it.
here is a example:
// First convert your string to array
$myString = $abilitato->id_zone; // Here your string separate with comas
$array = explode(',', $myString); // Here convert it to array
$value = 7; // Here you put the value that you want to check if is in array
// Check if exist a value in array
if (in_array($value, $array)){
echo "Exist in array";
}else{
echo "No exist in array";
}
This is the documentation of these functions: explode , in_array
Regards!

Cakephp 3 How to make session array

I am trying to write session in controller. My structure is
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
And I am trying this
Configure::write('Session', ['a' =>'1'])
But it is not working. How do this in cakephp 3 way
To write variable in Session in CakePHP 3 you need to write following code :
$this->request->session()->write('Your Key',Your_array);
To know more information you can visit here :
http://book.cakephp.org/3.0/en/development/sessions.html
To make things perfectly clear:
// code writing array to session
$a = [ "abc" => "word", "123" => 42, "?" => $b ];
$a["more"] = "if you need to add";
$a[] = "whatever";
$this->request->session()->write( 'my_array', $a );
// code reading array from session
$recall = $this->request->session()->read( 'my_array' );
debug( sprintf( "What's the word? [%s]", $recall["abc"] ) );
You can simply use
$session->write([
'key1' => 'blue',
'key2' => 'green',
]);
I am refering to
http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data
The answer is that this cannot be done in CakePHP 3.x
In vanilla PHP, it's possible to do this:
<?php
session_start();
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
var_dump($_SESSION);
?>
Which will output:
array(1) {
["a"]=> array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
}
This is correct, and what should happen.
In CakePHP, you cannot specify arrays in the session key. For example:
$this->request->session()->write('a[]', 1);
$this->request->session()->write('a[]', 2);
$this->request->session()->write('a[]', 3);
Will not work.
If you remove the [] the value will get overwritten. For example:
$this->request->session()->write('a', 1);
$this->request->session()->write('a', 2);
$this->request->session()->write('a', 3);
The value of $this->request->session()->read('a') would be 3. The values 1 and 2 have been overwritten. Again, this is to be expected because you're overwriting the key a each time. The equivalent vanilla PHP for this is:
$_SESSION['a'] = 1;
$_SESSION['a'] = 2;
$_SESSION['a'] = 3;
Due to the lack of an indexed array, $_SESSION['a'] gets overwritten each time. This is normal behaviour. It needs to have the indexes (e.g. ['a'][0], ['a'][1], ...) to work!
The other answers where they have given things like key1 and key2 are not appropriate. Because there are many situations where you want everything contained within an indexed array. Generating separate key names is wrong for this type of scenario.
My edit of the accepted answer was rejected, so I present the - seemingly necessary - explicit code example, for the benefit of #Andy and others.
// code to write to session
$a = [ 0 => "zero", 1 => "one", 2 => "two" ];
$a[] = "three";
$this->request->session()->write( 'my_array', $a );
// code to read from session
$z = $this->request->session()->read( 'my_array' );
debug( $a[3] ); // outputs "three"

Resources