0

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

1
  • Is $id_n_qty array always 1 array in it? Commented Dec 6, 2013 at 7:11

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think it needs $id_n_qty values. Not keys.
Its keys are product id and its value are quantity
its will throw an error Illegal offset type if you have tried
0

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.

1 Comment

@ravisoni I was actually thinking of the array_intersect_key logic backwards. I have corrected answer, which is actually even simpler than before
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.