Home > Blockchain >  How to explicitly check if there is an index in an array
How to explicitly check if there is an index in an array

Time:03-05

I have an array that looks like this

array [
    'product1' => [
        'product_amount' => 123,
    ],
    'product2' => [
        'product_amount_price' => 123
    ]
]

The issue I'm having is that I need to check if only product_amount_price is in the array, and if it is then do one thing otherwise do something else.

if(in_array('product_amount_price', $productArr))
{
    $productAmount = $productArr['product_amount_price'];
}else{
    $productAmount = $productArr['product_amount'];
}

dd($productAmount);

And what happens is if I land up on a product that has product_amount I get this error

Undefined index: product_amount_price

CodePudding user response:

You need to loop the array first, then use the in_array() method for each of the element, something like this:

foreach ($productArr as $product)
{
  if (in_array('product_amount_price', $product)
  {
    ...
  }
  ...
}

You need to make a loop first because the product_amount_price property is not on the first layer of your array, but the second.

CodePudding user response:

I found the answer. I had to use array_key_exists and not in_array

  • Related