0

I need to be able to swap given values if they are present in a multidimensional array.

$cars = array
(
  array("Volvo", "Silver", "Silver Metallic"),
  array("BMW", "Red", "Sunset Red")
);

For example if I'm given the following values within an object:

$myobject->make  = "Volvo";
$myobject->color = "Silver Metallic";

I need to use the array above to return

Silver

Not sure how to plug it all together.

echo $cars[0][$myobject->make]...

3 Answers 3

3
$cars = [
  ['Volvo', 'Silver', 'Silver Metallic'],
  ['BMW', 'Red', 'Sunset Red'],
];

$make = 'Volvo';
$color = 'Silver Metallic';

$result = NULL;
foreach ($cars as $c) {
  if ($c[0] === $make && $c[2] === $color) {
    $result = $c[1];
    break;
  }
}
if ($result !== NULL) {
  echo "found color: ".$result;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Depending how this array is set up, you could do something like this

$key = array_search('Silver Metallic', array_column($cars, '2'));

In your example, $key is 0, so you can then do something like

echo 'Color is ' . $cars[$key][1];

Not as scalable as foreach, but it could work for a limited subset of data like this

2 Comments

This wouldn't always work if you had two cars with the color Silver Metallic.
As I said, it's not scalable. Without know what you're trying to do here, it's simply an alternative way on a limited subset of data
0

Here you can pass your search data into the function as an array and leave any one field as an empty string ''... the function will return the missing field.

<?php

$cars = array(
  array("Volvo", "Silver", "Silver Metallic"),
  array("BMW", "Red", "Sunset Red")
);

function getSpecificValue($cars, $data)
{
    foreach ($cars as $car) {

        if ($data['make'] === '') {
            if ($car[1] === $data['color'] && $car[2] === $data['color_name']) {
                return $car[0];
            }
        } elseif ($data['color'] === '') {
            if ($car[0] === $data['make'] && $car[2] === $data['color_name']) {
                return $car[1];
            }
        } elseif ($data['color_name'] === '') {
            if ($car[0] === $data['make'] && $car[1] === $data['color']) {
                return $car[2];
            }
        }
    }
}

$data = [
    'make'       => 'BMW',
    'color'      => 'Red',
    'color_name' => '',
];

$result = getSpecificValue($cars, $data);

var_dump($result);

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.