Weird is_array() behaviour in PHP - php

I have form with several fields I want to store those values in a session variable. Some of those fields should be 0 if the user doesn't fill them in.
A print_r($_POST) after submitting the form shows:
[report] => Array
(
[a_name] => Array
(
[0] =>
)
[a_id_card] => Array
(
[0] =>
)
[a_total] =>
Yet, after running the following PHP code, it seems that "a_name" and "a_id_card" are not interpreted as arrays. Any ideea why?
if (isset($_POST['submit'])) {
foreach ($_POST as $key => $value) {
if (!is_array($key) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}

think you want to write this - is_array($value)

$key is the string 'report'. So is_array($key) == false. However $_POST[$key] or $value is an array.

The key is never an array. It is always a scalar or string. The value, on the other hand, can be an array.

Maybe you want look only $_POST['report'], and check if 'value' is or not an array (not key):
if (isset($_POST['submit'])) {
foreach ($_POST['report'] as $key => $value) {
if (!is_array($value) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}

Related

PHP str_replace Array Key pair

This may be a newbie question, but I am not getting it .
I have an array say :
$form = Array
(
[Resource_ID] => 5251
)
and I want the output as
$form = Array
(
[Resource ID] => 5251
)
Underscore should be replaced by a space.
I tried
foreach($form as $key => $value)
{
$form [$key] = str_replace("_"," ",$form [$key]);
}
But this is not working !
Can anyone tell me where I am going wrong ?
You should use such code
foreach($form as $key => $value)
{
$abc[str_replace("_"," ",$key)] = $value;
// unset($abc[$key]); <- this could cause problem
}
or even
foreach($form as $key => $value)
{
$pos = strpos($key,'_');
if ($pos !== false) {
$abc[str_replace("_"," ",$key)] = $value;
unset($abc[$key]);
}
}
But in both cases you should consider what to do if you have keys: key 1 and key_1. It seems that you can override value or even remove it (depending if you will use unset or not).

Get keys from multidimensional array according to other keys

I have a multidimensional array like this which I converted from JSON:
Array (
[1] => Array (
[name] => Test
[id] => [1]
)
[2] => Array (
[name] => Hello
[id] => [2]
)
)
How can I return the value of id if name is equal to the one the user provided? (e.g if the user typed "Test", I want it to return "1")
Edit: Here's the code that works if anyone wants it:
$array = json_decode(file_get_contents("json.json"), true);
foreach($array as $item) {
if($item["name"] == "Test")
echo $item["id"];
}
The classical solution is to simply iterate over the array with foreach and check the name of each row. When it matches your search term you have found the id you are looking for, so break to stop searching and do something with that value.
If you are using PHP 5.5, a convenient solution that works well with less-than-huge data sets would be to use array_column:
$indexed = array_column($data, 'id', 'name');
echo $indexed['Test']; // 1
You can use this function
function searchObject($value,$index,$array) {
foreach ($array as $key => $val) {
if ($val[$index] === $value)
return $val;
}
return null;
}
$MyObject= searchObject("Hello","name",$MyArray);
$id = $MyObject["id"];
You can do it manually like, in some function:
function find($items, $something){
foreach($items as $item)
{
if ($item["name"] === $something)
return $item["id"];
}
return false;
}
here is the solution
$count = count($array);
$name = $_POST['name']; //the name which user provided
for($i=1;$i<=$count;$i++)
{
if($array[$i]['name']==$name)
{
echo $i;
break;
}
}
enjoy
Try this:
$name = "Test";
foreach($your_array as $arr){
if($arr['name'] == $name){
echo $arr['id'];
}
}

How to compare textbox value if exist in 2d array?

I have this code and I need to compare the user input and the hardcoded 2d array. Can somebody help me with this? Thanks!
if (isset($_POST['submit']))
{
$array = array
(
0=>array
( 'username'=>'Art',
'password'=>'p#ssw0rd',
'user_id'=>'1'
),
1=>array
( 'username'=>'Berto',
'password'=>'1234',
'user_id'=>'2'
),
2=>array
( 'username'=>'Carrie',
'password'=>'5678',
'user_id'=>'3'
),
3=>array
( 'username'=>'Dino',
'password'=>'qwer',
'user_id'=>'4'
),
4=>array
( 'username'=>'Ely',
'password'=>'asdf',
'user_id'=>'5'
)
);
if(in_array($_POST['user'], $users))
{
$key = array_search($_POST['user'], $users);
I want to match the username if it exist through the 2d array. It is also the same for the password field.
You can do this through foreach loop
foreach($array as $key=>$value)
{
if($value['username'] == $_POST['user'] && $value['password'] == $_POST['pwd'])
{
// do whatever you want to do here
}
}
function searchForValue($fkey, $uvalue, $array) {
foreach ($array as $key => $val) {
if ($val[$fkey] == $uvalue) {
return $key;
}
}
return null;
}
call it like this
$id = searchForValue('username', $_POST['user'], $<yourarray>);
in case of password search
$id = searchForValue('password', $_POST['pass'], $<yourarray>);
You've defined your array name as $array but using $users in the in_array().
Anyways, suppose you use the correct name, you can match like this:
foreach ($users as $key => $item)
{
if ($item['username'] === $_POST['user'] &&
$item['password'] === $_POST['password'])
return $key;
return false;
}

fetch value in multidimensional associative array?

I have a SESSION array $_SESSION['cart']
for example it has value as
Array
(
[0] =>
[1] => Array
(
[item_id] => 1420
[item_qty] => 1
)
[2] => Array
(
[item_id] => 1522
[item_qty] => 1
)
)
Now let's say I have item_id = 1420
now I want to increase the item_qty for item_id = 1420 and also I have to set it in that SESSION array.
What I tried it :
foreach($_SESSION['Cartquantity'] as $key => $d)
{
if(isset($d)) {
if($d['item_id'] == $_GET['item_id'])
{
$d['item_quntity'] = $d['item_quantity']+1;
}
}
else{
}
}
It's not working ?
You're iterating over $_SESSION['Cartquantity'] but have told us that the array is stored in $_SESSION['cart'].
Also, this:
$d['tem_quntity'] = $d['item_quantity']+1;
Should be:
$d['item_qty'] = $d['item_qty']+1;
Finally, you'll need to make $d a reference by prepending an ampersand (&) to it in the foreach condition.
foreach($_SESSION['cart'] as $key => &$d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$d['item_qty'] = $d['item_qty']+1;
}
}
else{
}
}
Use reference &$d
foreach($_SESSION['Cartquantity'] as $key => &$d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$d['tem_quntity'] = $d['item_quantity']+1;
}
}
else{
}
}
or
foreach($_SESSION['Cartquantity'] as $key => $d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$_SESSION['Cartquantity'][$key]['item_quntity'] = $d['item_quantity']+1;
}
}
else{
}
}
change this
$d['tem_quntity'] = $d['item_quantity']+1;
to
$d['item_qty'] = $d['item_qty']+1;
you can call by
foreach ($_SESSION['Cartquantity'] as $value))
{
if(isset($value))
{
if($value['item_id'] == $_GET['item_id'])
{
$value['item_quntity'] = $value['item_quantity']+1;
}
}
else
{
}
}
Try to check for !empty($array)
if(!empty($d))
because it array so you need to check for if its do not have any elements inside of it.
If you want to know if the array is defined , then use isset($d).
If you want to know if a particular key is defined, use isset($d['item_id']).
If you want to know if an array has not empty and has key value pairs , use !empty($d).
use it:
foreach($_SESSION['cart'] as $key => $d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$d['tem_quntity'] = $d['item_qty']+1;
}
}
else{
}
}
foreach($_SESSION['cart'] as $key=>$val)
{
foreach($val as $subK)
{
if($_GET["item_id"]==$subk["item_id"])
{
$_SESSION['cart'][$key]["item_id"]=$_SESSION['cart'][$key]["item_quantity"]+1;
}
}
}

Wildcard array loop in PHP

I have an array which contains a great deal of data, which has been generated from a JSON file. Most of the data is used to populateinput elements, but some of the keys contain hidden, default values to be used for calculations later.
The array looks something like this:
[name] => 'My App'
[default_E17] => 0.009
[default_H17] => 0.0236
[default_K17] => 50
[default_P17] => 0.0118
[default_E19] => 0.03
I want to loop over all default_* keys, and output them using HTML. Essentially, I want a foreach loop, but only for the keys whose format matches default_*. Does anyone know if this is possible?
Please note that the values in the array before [default_*] keys is variable length, so I cannot easily use an array_splice().
You use strpos($key, "default_") === 0 to show that it start with default_ and its not in the middle or end
$array = array();
$array['name'] = 'My App';
$array['default_E17'] = "0.009";
$array['default_H17'] = "0.0236";
$array['default_K17'] = "50";
$array['default_P17'] = "0.0118";
$array['default_E19'] = "0.03";
$array['E19_default_test'] = "1.03";
echo "<pre>";
* You can use foreach *
$list = array();
foreach ( $array as $key => $value ) {
if (strpos($key, "default_") === 0) {
$list[$key] = $value;
}
}
var_dump($list);
You can also use array_flip with array_filter
$array = array_flip(array_filter(array_flip($array),function($var) { return (strpos($var, "default_") === 0);}));
var_dump($array);
You can also use FilterIterator
class RemoveDefaultIterator extends FilterIterator {
public function accept() {
return (strpos($this->key(), "default_") === 0);
}
}
$list = new RemoveDefaultIterator(new ArrayIterator($array));
var_dump(iterator_to_array($list));
They would all Output
array
'default_E17' => string '0.009' (length=5)
'default_H17' => string '0.0236' (length=6)
'default_K17' => string '50' (length=2)
'default_P17' => string '0.0118' (length=6)
'default_E19' => string '0.03' (length=4)
foreach( $arr as $k => $v ) { //iterate the array
if( strpos($k, 'default_') !== FALSE ) //search if the key contains 'default_'
$default_values[] = $v; // if so, store the values for the 'default_' keys
}
Just iterate over your array
Foreach( $inputArray AS $key=>$val ) {
// check if key is the one we need
if( ... ) {
// it is - deal with it
}
}
depending of the keys you use if() can be simple substr() or regexp matching.
You can use a FilterIterator for this.
Its essetially the same as looping over the whole array, because that's the only way really, but it strips you from doing this in your productive loop, thus generating less noise.
Here's how:
class Default_FilterIterator extends FilterIterator
{
public function accept()
{
if (strpos($this->key(), 'default') === 0) {
return true;
}
return false;
}
}
$yourArray = array('default_stuff' => 'foo', 'otherstuff' => 'bar');
$filterdArray = new Default_FilterIterator(new ArrayIterator($yourArray));
foreach ($filteredArray as $key => $value) {
//deal only with default values here
}
foreach ($your_array as $key => $value) {
// check if the $key starst with 'default_'
if (substr($key, 0, 8) == "default_") {
//do your thing...
echo "<input type='text' value='" . $value . "'>";
}
}

Categories