0

Am working on some set of PHP array. Am trying to loop through each of them and check the array whose name is equal to Josw Acade. Am using a for loop but I get zero after extracting the data. I want to store the data in an array.

Array

array:6 [
  0 => array:4 [
    "id" => 1
    "name" => "Josw Acade"
    "value" => "Unlimited"
    "plan_type" => "Superior"
  ]
  1 => array:4 [
    "id" => 2
    "name" => "Verbal"
    "value" => "true"
    "plan_type" => "Superior"
  ]
  2 => array:4 [
    "id" => 12
    "name" => "Josw Acade"
    "value" => "$1,500,00"
    "plan_type" => "Classic"
  ]
  3 => array:4 [
    "id" => 13
    "name" => "Leon"
    "value" => "true"
    "plan_type" => "Classic"
  ]
  4 => array:4 [
    "id" => 14
    "name" => "One Time"
    "value" => "true"
    "plan_type" => "Classic"
  ]
  5 => array:4 [
    "id" => 15
    "name" => "Deat"
    "value" => "$25,000"
    "plan_type" => "Classic"
  ]
  6 => array:4 [
    "id" => 23
    "name" => "Josw Acade"
    "value" => "$100,000"
    "plan_type" => "Essential"
  ]
]

Logic

$Inst = [];
for($med = 0; $med < count($array); $med++){
    if($med['name'] == "Josw Acade"){
        $Inst = $med['value'];
    }
}

dd($Inst);
1
  • what is $pkg ... you have a loop initializing a variable $med to 0 then you are using that variable as an array $med['name'] ? Commented Nov 7, 2019 at 8:55

4 Answers 4

1

You can use array_filter with callback

$filtered = array_filter($array, function($v){ return $v['name'] == 'Josw Acade'})
print_r($filtered);
Sign up to request clarification or add additional context in comments.

Comments

1

Your variables is not corretly set in the for loop, you are setting $med = 0 and acessing $med as an array.

Use filter, that runs a condition on each element and returns the items that satisfy that condition.

array_filter($array, function ($item) {
    return $item['name'] === 'Josw Acade';
});

In general you don't have to make old school arrays anymore, foreach does the same.

$results = [];

foreach($array as $item) 
{
    if ($item['name'] === 'Josw Acade') {
        $results[] = $item['value'];
    }
}

Comments

0

You are looping through array; so on each iteration to get values; you need to pass index value and you are missing that. You are using $med as index.

Here is code.

$Inst = [];
for($med = 0; $med < count($array); $med++){
    if($array[$med]['name'] == "Josw Acade"){
        $Inst[] = $array[$med]['value'];
    }
}

Comments

0

there is many way to do this but according to me the best way to use array_filer()

array_filter($array, function ($item) {
    return $item['name'] === 'Josw Acade';
});

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.