I've two arrays $products
and $id_n_qty
$id_n_qty array contains Product id and its quantity where $products array contains all products with their IDs and name.
$products = array(1=>"Shampoo",2=>"Towel");
$id_n_qty = array(1=>3);
My question is how can i get the Product name when i have the $id_n_qty
with me without using php foreach
?
Thanks
Try with array_keys
like
$key_val = array_keys($id_n_qty);
echo $products[$key_val[0]];
Considering that you have only single array in the $id_n_qty
.
If you are saying that the key for $id_n_qty
matches the keys in $products
, you simply need to investigate the key values.
$product_names = array_intersect_key($products, $id_n_qty);
Note that this gives you the product names for all key values that are in $id_n_qty, thus the $product_names variable is an array.
If like you said you have single array, you can get the ID like this:
// Getting ID
$id = key(reset($id_n_qty));
// Getting Quantity
$qty = $id_n_qty[$id];
But I must say this is not an elegant way to do it. You could get the id and quantity as seperate item then it will be more elegant to get it:
// First item is ID and second item is Quantity
$id_n_qty = array(1, 3);
// Getting ID and Quantity:
list($id, $quantity) = $id_n_qty;
As you see it is easy and looking good. If you can convert the array to this that is.