0

I would want to abstract a value of a property in the below array. May I know how can I do with php?

print_r($array);

Array
(
   [0] => {property1: 'value12', property2: 'value12', property3: 'value13'}
   [1] => {property1: 'value21', property2: 'value22', property3: 'value23'}
)

May I know how to read the value of attribute property1 of each array?

3
  • is the value inside Array[0]{... an object or an array? Commented Jan 16, 2021 at 5:52
  • @caramba, object Commented Jan 16, 2021 at 5:54
  • 3v4l.org/HatcX ? Commented Jan 16, 2021 at 5:55

1 Answer 1

2

If you have an array with objects this might be the way to go:

$myArrayWithObjects = [
    0 => (Object) ['property1' => 'value12', 'property2' => 'value12', 'property3' => 'value13'],
    1 => (Object) ['property1' => 'value21', 'property2' => 'value22', 'property3' => 'value23']
];

echo 'Array with Objects: ' . $myArrayWithObjects[1]->property3 . "\n";
// prints: Array with Objects: value23

you can loop over the "first array" and use the object like so:

foreach($myArrayWithObjects as $myObject) {
    echo 'Array with Objects foreach: ' . $myObject->property2 . "\n";
}

if it is an array with arrays go this way:

$myArray = [
    0 => ['property1' => 'value12', 'property2' => 'value12', 'property3' => 'value13'],
    1 => ['property1' => 'value21', 'property2' => 'value22', 'property3' => 'value23']
];

echo 'Array with arrays: ' . $myArray[1]['property3'] . "\n";
// prints: Array with arrays: value23

and the foreach loop for array with arrays accordingly:

foreach($myArray as $innerArray) {
    echo 'Array with arrays foreach: ' . $innerArray['property2'] . "\n";
}

you can play with it online here: http://sandbox.onlinephpfunctions.com/code/7b8f5740350278f811ab9f998b9501c154697abf

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

2 Comments

Maybe add an example using foreach() ? "... of each array ?"
@Syscall thanks for feedback! I've updated the answer

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.