0

I have an array variable $var. When I var_dump($var), it shows the following:

array(2) {
   [0] => array(3) {
         ["name"] => string(7) "Ferrari" 
         ["speed"] => int(120)
         ["isActive"] => bool(true)
         }array(3) {
         ["name"] => string(7) "Porsche" 
         ["speed"] => int(100)
         ["isActive"] => bool(false)
         }
}

The question is: I want to access these values. For example, i want to save the speed value of Ferrari into a variable $speed.

Something like check every element of array, If "name" = Ferrari, Set $speed= corresponding int value of choosen element of array.

What is the syntax of this in PHP.

Thanks in advance.

2
  • 1
    what have you tried? It's simple array and loop syntax that you're asking for. Commented Feb 11, 2014 at 22:03
  • You use a loop for that. foreach ($yourarray as $element) then the $element varialbe is your key value array Commented Feb 11, 2014 at 22:03

3 Answers 3

1
$speed = null;
foreach ($var as $car) {
    if ($car['name'] == 'Ferrari') {
        $speed = $car['speed'];
    }
}
echo $speed;

Would be more reusable if you'll extend the array $var.

You can find basics of PHP here: W3Schools

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

Comments

0

You just need to get the value from the array. Check isset to make sure the value exists if you want.


$speed = (isset($var[0]['speed'])) ? $var[0]['speed'] : 0;

Comments

0

pls try this :

$speed = 0;
if (isset($var[0]["name"]) && isset($var[0]["speed"]) && $var[0]["name"]=="Ferrari"){
    $speed = $var[0]["speed"];
}

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.